JSFiddle - React, Tailwind, and code Playground
by levrun
HTML
<script src="https://cdn.jsdelivr.net/jasmine/2.5.2/jasmine.js"></script>
<script src="https://cdn.jsdelivr.net/jasmine/2.5.2/jasmine-html.js"></script>
<script src="https://cdn.jsdelivr.net/jasmine/2.5.2/boot.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/jasmine/2.5.2/jasmine.css">
TypeScript
class StringCalculator {
public COMMA_SEPARATOR:string = ",";
public NEW_LINE:string = "\n";
public SPACE:string = " ";
public EMPTY:string = "";
public NEW_SEPARATOR_MARKER:string = "//";
add(input:string) {
if(input.length === 0) {
return 0;
}
let separator:string = this.COMMA_SEPARATOR;
if(input.substring(0, 2) === this.NEW_SEPARATOR_MARKER) {
let matches = input.match(/\[(.*?)\]/g);
if(matches !== null) {
for(let n:string of matches) {
separator = n.substring(1, n.length);
separator = separator.substring(0, separator.length -1);
input = this.replaceAll(input, separator, this.COMMA_SEPARATOR);
}
input = input.substring(input.indexOf(this.NEW_LINE) + 1, input.length);
separator = this.COMMA_SEPARATOR;
} else {
separator = input.substring(2,3);
input = input.substring(4, input.length);
}
}
input = input.replace(this.NEW_LINE, separator);
let sum:int = 0;
let array[] = input.split(separator);
let errors[] = [];
for(let numString:string of array) {
let num:int = parseInt(numString);
if(num > 1000) {
continue;
}
if(num < 0) {
errors.push(numString);
}
sum = sum + num;
}
if(errors.length > 0) {
let errorsString:string = this.EMPTY;
for(let i:string in errors) {
errorsString = errorsString + errors[i] + this.SPACE;
}
throw new Error("negatives not allowed " + errorsString);
}
return sum;
}
escapeRegExp(str:string) {
return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
replaceAll(str, find, replace) {
return str.replace(new RegExp(this.escapeRegExp(find), 'g'), replace);
}
}
describe("String...