A simple string calculator that can add numbers from a given string input with customizable delimiters and validation options.
The calculator is implemented using two classes:
- Handles basic addition logic.
- Ensures numbers larger than the allowed maximum are ignored.
- Throws errors for negative numbers if required.
- Parses input strings and extracts numbers.
- Supports custom delimiters, multi-character delimiters, and multiple delimiters.
- Converts input into a format suitable for
Calculator
to process.
I followed the TDD methodology by first writing failing test cases before implementing the functionality. Each feature is built incrementally, ensuring all tests passed before moving to the next. I have completed all the steps of TDD Kata 1.

const calculator = new StringCalculator();
const result = calculator.add("1,2,3"); // Returns 6
console.log(result); // 6
calculator.add("1,2"); // Returns 3
calculator.add(""); // Returns 0
calculator.add("5"); // Returns 5
calculator.add("1,2,3,4,5"); // Returns 15
calculator.add("1\n2,3"); // Returns 6
You can define a custom delimiter by specifying it at the beginning of the string using the pattern:
//[delimiter]\n[numbers…]
calculator.add("//;\n1;2"); // Returns 3
calculator.add("1,-2,3"); // Throws "negative numbers not allowed -2"
calculator.add("-1,-2,-3"); // Throws "negative numbers not allowed -1,-2,-3"
calculator.add("2,1001"); // Returns 2 (1001 is ignored)
calculator.add("//[***]\n1***2***3"); // Returns 6
calculator.add("//[*][%]\n1*2%3"); // Returns 6
calculator.add("//[***][%%]\n1***2%%3"); // Returns 6
By default, negative numbers are not allowed. If a negative number is found, an error will be thrown.
calculator.add("-9"); // Throws "negative numbers not allowed -9"
calculator.add("1,2,-3"); // Throws "negative numbers not allowed -3"
To allow negative numbers, set allowOnlyPositiveNumbers to false:
calculator.add("1,2,-3", false); // Returns 0 (default sum behavior)
By default, numbers larger than 1000 are ignored.
calculator.add("1,1001,2"); // Returns 3 (1001 is ignored)
calculator.add("1001"); // Returns 0
You can change this limit by setting maxAllowedNumber:
calculator.add("1,2000,2", true, 2000); // Returns 2003 (2000 is now included)
You can define a custom delimiter by specifying it at the beginning of the string in the format: "//[delimiter]\n[numbers…]"
calculator.add("//;\n1;2"); // Returns 3 (using `;` as a delimiter)
You can use a delimiter of any length.
calculator.add("//[***]\n1***2***3"); // Returns 6
You can define multiple custom delimiters of any length.
calculator.add("//[*][%]\n1*2%3"); // Returns 6
calculator.add("//[***][%%]\n1***2%%3"); // Returns 6