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

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"));
All lessons in this course
- E1 — Expression Evaluator (part 1: + and - LTR)
- E2 — Log Analyzer (simple filters & counters)
- E3 — Promise Pool/Queue (async concurrency)