Skip to content

Instantly share code, notes, and snippets.

@aleixmorgadas
Created September 8, 2021 08:06
Show Gist options
  • Save aleixmorgadas/4ac04cde3ab2b811d77e906648c06517 to your computer and use it in GitHub Desktop.
Save aleixmorgadas/4ac04cde3ab2b811d77e906648c06517 to your computer and use it in GitHub Desktop.
const CUSTOM_DELIMITER_PATTERN = "//";
const DEFAULT_DELIMITER = ",";
const DELIMITIER_POSITION = 2;
const NUMBERS_START_POSITION = 4;
const parseInput = (input) => {
if (input.startsWith(CUSTOM_DELIMITER_PATTERN)) {
return {
delimiter: input[DELIMITIER_POSITION],
rawNumbers: input.substring(NUMBERS_START_POSITION, input.length)
};
}
return {
delimiter: DEFAULT_DELIMITER,
rawNumbers: input
};
};
const calculator = (input) => {
if (input.length === 0) return 0;
const { delimiter, rawNumbers } = parseInput(input);
if (rawNumbers.includes("-")) {
throw Error("negatives not allowed");
}
const numbers = rawNumbers.replaceAll("\n", ",").split(delimiter);
return numbers.reduce((prev, next) => parseInt(prev) + parseInt(next), 0);
};
describe("Calculator", () => {
it("simple case", () => {
const result = calculator("");
expect(result).toBe(0);
});
it("one number", () => {
const result = calculator("1");
expect(result).toBe(1);
});
it("couple of numbers", () => {
const result = calculator("1,3");
expect(result).toBe(4);
});
it("unknown amount of numbers", () => {
const result = calculator("1,3,5,5,20");
expect(result).toBe(34);
});
it("handle new lines between numbers", () => {
const result = calculator("1\n2,3");
expect(result).toBe(6);
});
it("support different delimiters", () => {
const result = calculator("//;\n1;2");
expect(result).toBe(3);
});
it("negative numbers", () => {
expect(() => calculator("1,4,-1")).toThrow("negatives not allowed");
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment