Upantor

Posted on: December 27, 2025

From Basic Arithmetic to Advanced Expression Evaluation

After creating interactive games and data-persistent applications, I set out to tackle a new challenge: building a fully-featured calculator that could handle complex mathematical expressions. This project represents my journey into advanced JavaScript patterns, library integration, and professional-grade error handling.

The Challenge: Beyond Simple Arithmetic

Most beginner calculators handle only basic operations. I wanted to build something that could:

  • Evaluate complex mathematical expressions
  • Remember previous calculations across browser sessions
  • Provide professional keyboard and button input
  • Handle edge cases and errors gracefully
  • Follow object-oriented design principles

Technical Implementation

Object-Oriented Architecture

I implemented a clean, class-based structure that separated concerns and followed OOP principles:

class Calculator {
  constructor() {
    // Encapsulated state management
    this.previousAns = this.loadFromCookies();
    this.setupEventListeners();
    this.initializeDisplay();
  }
}

Advanced Library Integration

Instead of using the dangerous eval() function, I integrated the robust math.js library for safe expression evaluation:

let result = math.evaluate(expression);
// Safe, accurate mathematical evaluation
// Handles complex operations and follows proper order of operations

Cross-Session Memory

I implemented cookie-based persistence to remember the previous answer:

document.cookie = `previousAns=${result}; path=/;`;
// Allows users to continue calculations across browser sessions

Key Features

Professional Mathematical Engine

  • Complex Expression Parsing: Handles parentheses, multiple operators, and the “Ans” variable
  • Order of Operations: Properly evaluates expressions using mathematical precedence rules
  • Decimal Support: Full floating-point arithmetic with precision control

Dual Input System

  • Button Interface: Clean, responsive button grid with visual feedback
  • Full Keyboard Support: Type expressions directly with real-time validation
  • Smart Input Filtering: Prevents invalid characters while allowing mathematical operators

Error Handling & Recovery

  • Graceful Error Display: Professional error messages without breaking the UI
  • Input Validation: Prevents malformed expressions before evaluation
  • Recovery Options: Easy return to calculation after errors

User Experience

  • “Calculating…” Animation: Visual feedback during evaluation
  • Previous Answer Memory: “Ans” button recalls last calculation
  • Clear/DEL Functions: Proper editing capabilities
  • Responsive Design: Works across device sizes

Technical Challenges Solved

Challenge 1: Safe Expression Evaluation

Problem: Using eval() is dangerous and limited for mathematical expressions.
Solution: Integrated math.js library for secure, accurate mathematical evaluation.

Challenge 2: Expression Parsing

Problem: Splitting user input into mathematical tokens while preserving meaning.
Solution: Implemented robust tokenization that handles variables, operators, and parentheses.

Challenge 3: State Persistence

Problem: Remembering calculations between sessions without server infrastructure.
Solution: Cookie-based storage with proper parsing and expiration handling.

Challenge 4: Input Validation

Problem: Preventing invalid keyboard input while maintaining typing flexibility.
Solution: Real-time key filtering with comprehensive allowed character sets.

Architectural Decisions

Why a Class-Based Approach?

  • Encapsulation: All calculator logic contained in one place
  • Reusability: Easy to instantiate multiple calculators
  • Maintainability: Clear separation of concerns
  • Professional Patterns: Industry-standard JavaScript architecture

Why math.js Over eval()?

  • Safety: No security vulnerabilities
  • Accuracy: Proper mathematical evaluation
  • Features: Built-in scientific functions
  • Reliability: Well-tested library

Why Cookies Over LocalStorage?

  • Simplicity: Direct value storage without serialization
  • Cross-tab Access: Available across all tabs
  • Automatic Expiration: Built-in management
  • No Setup Required: Works out of the box

Learning Journey

This project taught me several critical concepts:

1. Library Integration

How to properly research, select, and integrate third-party libraries into a project.

2. Mathematical Computing

The complexities of expression parsing, tokenization, and evaluation.

3. Professional Error Handling

Graceful degradation and user-friendly error messages for mathematical operations.

4. State Management Patterns

Managing application state across user interactions and browser sessions.

The Most Satisfying Moment

The first time I typed “2+2×3” and saw it correctly evaluate to 8 (not 12) was a breakthrough. It demonstrated that I had built something that understood mathematical rules, not just string manipulation.

Areas for Future Enhancement

As version 1.0, I recognize opportunities for growth:

  • Scientific functions (sin, cos, tan, log, sqrt)
  • Memory functions (M+, M-, MR, MC)
  • Expression history and recall
  • Theme customization
  • Advanced keyboard shortcuts
  • Unit conversion capabilities

Technical Skills Developed

Advanced JavaScript Patterns

  • Class-based architecture with proper encapsulation
  • Event delegation and keyboard handling
  • Asynchronous operations with visual feedback
  • Cookie management and data persistence

Mathematical Computing

  • Expression parsing and tokenization
  • Operator precedence handling
  • Error detection and recovery
  • Decimal and negative number management

User Experience Design

  • Dual input systems (keyboard + buttons)
  • Real-time validation and feedback
  • Professional error states
  • Responsive interface design

Project Evolution

This calculator represents a significant step forward from my earlier projects:

Before: Simple interactive elements with basic logic
Now: Complex mathematical engine with state persistence

Before: Tutorial-following implementation
Now: Architect-designed system with proper patterns

Before: One-off solutions for specific problems
Now: General-purpose tool with extensible architecture

Conclusion: From Coder to Engineer

This calculator project marks a transition in my development journey. It’s not just about writing code that works—it’s about creating systems that are:

  • Robust: Handles edge cases and errors gracefully
  • Extensible: Built with patterns that allow easy feature addition
  • Professional: Follows industry standards and best practices
  • User-Centered: Designed with actual user workflows in mind

The skills I developed here—library integration, mathematical computing, state management, and professional architecture—form the foundation for building complex web applications. This calculator is more than a tool; it’s a demonstration of engineering thinking applied to web development.

The Project File

Bundling Preview...
  • index.html
  • script.js
  • style
    • caulculater.css
    • little.style.css
    • style.css
Files will show here

This project represents approximately 30 hours of development, testing, and refinement. It's where I learned that building something "simple" often involves solving complex problems in elegant ways—a lesson that defines professional software development.

About the Author – Upantor Paul

I’m Upantor Paul, a WordPress engineer and performance-focused developer specializing in building high-performance, scalable websites using custom PHP logic, clean architecture, and precision engineering. Through upantor.com, I document real-world development work, technical experiments, and code journals focused on Elementor optimization, WordPress internals, Core Web Vitals, and long-term maintainability.
Beyond my personal engineering projects, I also run WebWish Creation — a WordPress-oriented platform where I share tutorials, provide services, and build practical resources for site owners and businesses looking to create, manage, and scale reliable WordPress websites. This setup allows me to work from both an engineering and client-delivery perspective, keeping solutions technically solid and business-focused.

If you’d like to work directly with me, you can explore my portfolio to see real projects in action, or start a technical consultation to discuss custom WordPress functionality, performance optimization, or a conversion-focused build engineered around your business goals.

If you like it, consider sharing it with your friend.