0Pricing
JavaScript Academy · Lesson

E1 — Expression Evaluator (part 1: + and - LTR)

Implement a tiny evaluator that handles + and - left-to-right. Tokenize digits and operators, ignore spaces, and add simple guards.

What we will build

Goal: Evaluate tiny math strings with + and - only.

  • Tokenize numbers and operators
  • Ignore spaces
  • Compute left-to-right
  • Add simple error guards
E1 — Expression Evaluator (part 1: + and - LTR) — illustration 1

Tokenizer: numbers and ops

The tokenizer builds numbers from digits and returns an array like [12, "+", 3, "-", 4].

// Tokenize: split into numbers and operators; ignore spaces
function tokenize(expr) {
  if (typeof expr !== "string") return null;

  const tokens = [];
  let num = "";

  for (let i = 0; i < expr.length; i = i + 1) {
    const ch = expr[i];

    if (ch === " ") {
      // skip spaces
      continue;
    }

    if (ch >= "0" && ch <= "9") {
      // build number
      num = num + ch;
    } else if (ch === "+" || ch === "-") {
      // flush pending number
      if (num.length > 0) {
        tokens.push(Number(num));
        num = "";
      }
      tokens.push(ch);
    } else {
      // unsupported character
      return null;
    }
  }

  if (num.length > 0) tokens.push(Number(num));
  return tokens;
}

console.log("tokens:", tokenize("12 + 3 - 4"));
E1 — Expression Evaluator (part 1: + and - LTR) — illustration 2

All lessons in this course

  1. E1 — Expression Evaluator (part 1: + and - LTR)
  2. E2 — Log Analyzer (simple filters & counters)
  3. E3 — Promise Pool/Queue (async concurrency)
← Back to JavaScript Academy