Contained herein are implementations of the String Calculator Kata in several languages. It is used as a live coding exercise during interviews to explore a candidate's approach to test-driven development, incremental design, and refactoring.
The kata itself was created by Roy Osherove. The full problem statement lives at https://osherove.com/tdd-kata-1.
- Try not to read ahead.
- Do one task at a time. The trick is to learn to work incrementally.
- Only test for correct inputs — there is no need to test for invalid inputs for this kata.
- Remember to refactor after each passing test.
- Create a simple String calculator with a method
add(numberString)that returns an integer.- The method can take 0, 1, or 2 numbers and will return their sum.
An empty string returns
0. For example:"","1", or"1,2". - Start with the empty-string case, then one number, then two.
- The method can take 0, 1, or 2 numbers and will return their sum.
An empty string returns
- Allow the
addmethod to handle an unknown amount of numbers. - Allow the
addmethod to handle newlines between numbers in addition to commas. For example,"1\n2,3"should equal6. - Support different delimiters. To change a delimiter, the beginning
of the string contains a line of the form
"//[delimiter]\n". For example,"//;\n1;2"should return3. The first line is optional; all previous scenarios should still work. - Calling
addwith a negative number should throw an exception containing all of the negatives that were passed in.
Stop here if you are a beginner. Continue if you finished the steps above in under 30 minutes.
- Numbers bigger than 1000 should be ignored:
2 + 1001 = 2. - Delimiters can be of any length, given in the form
"//[delimiter]\n". For example,"//[***]\n1***2***3"should return6. - Allow multiple delimiters, given as
"//[delim1][delim2]\n". For example,"//[*][%]\n1*2%3"should return6. - Make sure multi-character delimiters also work when there are multiple of them.
- js/ — JavaScript with QUnit. Open
start.htmlfor the empty starter orindex.htmlfor a worked example. - php/ — PHP with PHPUnit. Run
rakefrom thephp/directory. - python/ — Python 3 with
unittest. Runpython -m unittestfrom thepython/directory.
Based on the String Calculator TDD Kata by Roy Osherove.