Skip to content

Instantly share code, notes, and snippets.

@carlos-talavera
Last active October 16, 2024 18:20
Show Gist options
  • Save carlos-talavera/ba4297bb95d5363e53f0aa0c2ba89cda to your computer and use it in GitHub Desktop.
Save carlos-talavera/ba4297bb95d5363e53f0aa0c2ba89cda to your computer and use it in GitHub Desktop.
Example of a function which takes a string of numbers separated by a specific delimiter and sums the numbers. Includes tests
import {sumNumbers} from "../core/string-calculator";
describe('StringCalculator', () => {
it('can handle null and empty strings', () => {
expect(sumNumbers(null)).toBe(0);
expect(sumNumbers('')).toBe(0);
});
it('can handle one number', () => {
expect(sumNumbers('18')).toBe(18);
});
it('can handle numbers separated by commas', () => {
expect(sumNumbers('5,10,15')).toBe(30);
});
it('can handle non-numeric values', () => {
expect(sumNumbers('a')).toBe(0);
expect(sumNumbers('8,a,10')).toBe(18);
});
it('can handle custom separators', () => {
expect(sumNumbers('//%/5%2')).toBe(7);
expect(sumNumbers('//%/4,6')).toBe(0);
expect(sumNumbers('//#/4#6')).toBe(10);
});
});
const DEFAULT_SEPARATOR = ',';
const CUSTOM_SEPARATOR_REGEX = /^\/\/(.)\//;
export function sumNumbers(input: string) {
if (!input) return 0;
const separator = extractSeparator(input);
const numbersString = getNumbersString(input);
return numbersString.split(separator).reduce(sum, 0);
}
function sum(accumulator: number, currentToken: string) {
return accumulator + parseTokenToNumber(currentToken);
}
function parseTokenToNumber(token: string) {
const parsedToken = Number(token);
return isNaN(parsedToken) ? 0 : parsedToken;
}
function extractSeparator(input: string) {
const customSeparatorMatch = input.match(CUSTOM_SEPARATOR_REGEX);
return customSeparatorMatch ? customSeparatorMatch[1] : DEFAULT_SEPARATOR;
}
function getNumbersString(input: string) {
return input.replace(CUSTOM_SEPARATOR_REGEX, '');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment