This is a simple Test-Driven Development (TDD) exercise to implement a string-based calculator that parses numbers and returns their sum.
- ✅ Start with the simplest test case of an empty string.
- ✅ Move to one and two numbers as next steps.
- ✅ Solve problems in the simplest manner so that you're forced to write tests you may not have initially thought of.
- ✅ Refactor your code after each passing test.
Create a simple String Calculator with the following method signature:
int add(string numbers)
- A
string
containing numbers separated by delimiters such as:- Commas
,
- New lines
\n
- Custom delimiters (defined by the user)
- Commas
- An
integer
which is the sum of the numbers in the input string.
Input | Output |
---|---|
"" |
0 |
"1" |
1 |
"1,5" |
6 |
"1\n2,3" |
6 |
"//;\n1;2" |
3 |
- ✅ Return
0
for an empty string. - ✅ Return the number itself if only one number is provided.
- ✅ Sum of two or more comma-separated numbers.
- ✅ Allow any number of comma-separated numbers.
- ✅ Allow new lines between numbers (e.g.
"1\n2,3"
). - ✅ Support custom delimiters:
- Format:
"//[delimiter]\n[numbers]"
- Example:
"//;\n1;2"
should return3
.
- Format:
- ❌ If any negative numbers are passed, the method should throw an exception:
- Error message:
"negative numbers not allowed: <negative_number>"
- If multiple negatives are found, list all in the message:
- Example:
"negative numbers not allowed: -1, -5"
- Example:
- Error message:
- Write a failing test.
- Write just enough code to make it pass.
- Refactor for cleanliness.
- Commit after each step to track progress clearly.
- Language: JavaScript (Node.js)
- Test Framework: Node’s built-in
assert
module (basic, beginner-friendly) - Git: For version control and committing each step
-
Clone the repo:
git clone https://github.com/Satish980/string-calculator-tdd-kata cd string-calculator
-
Run the code using Node:
node src/calculator.js
I’ve used Node’s built-in assert
module.
-
To run tests:
node tests/calculator.test.js
-
Example test:
const assert = require('assert'); assert.strictEqual(add("1,2,3"), 6);
Below is a screenshot of the calculator running and passing all test cases:

string-calculator-tdd-kata/
├── src/calculator.js # main calculator logic
├── tests/calculator.test.js # test cases
└── README.md # project documentation