Last active
February 11, 2021 06:02
-
-
Save giordanocardillo/3a94c6e5e4955b09e052fbebd58a41b8 to your computer and use it in GitHub Desktop.
String Calculator Kata in JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const calculator = (function(){ | |
function add(numberString){ | |
if (numberString === ''){ | |
return 0 | |
} | |
const delimiter = getDelimiter(numberString) | |
const formattedInput = formatInput(numberString) | |
return calculateSum(getNumbers(formattedInput, delimiter)) | |
} | |
function formatInput(input){ | |
const delimiterRegExp = /^(\/\/.*\n)/ | |
const matches = delimiterRegExp.exec(input) | |
if(matches && matches.length > 0){ | |
return input.replace(delimiterRegExp,'') | |
} | |
return input | |
} | |
function getDelimiter(input) { | |
const delimiters = [] | |
const multipleDelimiterRegexp = /(?:^\/\/)?\[([^\[\]]+)\]\n?/g | |
let matches = multipleDelimiterRegexp.exec(input) | |
while(matches !== null){ | |
delimiters.push(matches[1]) | |
matches = multipleDelimiterRegexp.exec(input) | |
} | |
if(delimiters.length > 0){ | |
return new RegExp('['+delimiters.join('')+']') | |
} | |
matches = /^\/\/(.*)\n/.exec(input) | |
if(matches && matches[1]){ | |
return matches[1] | |
} | |
return /[\n,]/ | |
} | |
function getNumbers(string, delimiter){ | |
return string.split(delimiter) | |
.filter(n => n !== '') | |
.map(n => parseInt(n)) | |
} | |
function calculateSum(numbers){ | |
const negatives = [] | |
const finalSum = numbers.reduce((sum, n) =>{ | |
if(n > 1000){ | |
return 0 | |
} | |
if(n < 0){ | |
negatives.push(n) | |
return 0 | |
} | |
return sum + n | |
},0) | |
if(negatives.length > 0){ | |
throw new Error('Negatives not allowed: '+negatives.join(',')) | |
} | |
return finalSum | |
} | |
return {add} | |
}()) | |
console.info(calculator.add('')) // 0 | |
console.info(calculator.add('1,2,3')) // 6 | |
console.info(calculator.add('1\n2,3')) // 6 | |
console.info(calculator.add('//;\n1;2;3')) // 6 | |
console.info(calculator.add('1001,2')) // 6 | |
console.info(calculator.add('//[**]\n1**2**3')) // 6 | |
console.info(calculator.add('//[*][%]\n1*2%3')) // 6 | |
console.info(calculator.add('//[..][%%]\n1..2%%3')) // 6 | |
console.info(calculator.add('-1,-3,2')) // 6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment