Skip to content

Instantly share code, notes, and snippets.

@danielyaa5
Created February 11, 2020 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielyaa5/923f90f9f67f5b16adfa3a669c9649d3 to your computer and use it in GitHub Desktop.
Save danielyaa5/923f90f9f67f5b16adfa3a669c9649d3 to your computer and use it in GitHub Desktop.
const concat = (...elements) => elements.reduce((acc, el) => el ? acc.concat(el) : acc, []);
const getPowerWord = power => ['', 'Thousand', 'Million', 'Billion'][power];
const getTens = tens => ['Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninetey'][tens - 2]
const below20 = num => ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eightteen', 'Nineteen'][num]
const below100 = num => num < 20 ? [below20(num)] : concat([getTens(Math.floor(num / 10)), below20(num % 10)]);
const hundrify = num => Math.floor(num / 100) ? [below20(Math.floor(num / 100)), 'Hundred'] : '';
const below1000 = num => concat(hundrify(num), below100(num % 100));
const powerify = (num, power) => num ? concat(below1000(num), getPowerWord(power)).join(' ') : [];
const solution = (integer) => {
if (integer === 0) return 'Zero';
if (integer < 1000) return below1000(integer);
const result = [];
let power = 0;
let curr = integer;
while (curr >= 1) {
result.unshift(powerify(curr % 1000, power++));
curr = Math.floor(curr / 1000);
}
return result.join(' ');
}
console.log(solution(3542), '3542')
console.log(solution(9840), '9840')
console.log(solution(11), '11')
console.log(solution(123915), '123915')
console.log(solution(99999), '99999')
console.log(solution(308999123), '308999123')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment