Created
February 11, 2020 21:28
-
-
Save danielyaa5/923f90f9f67f5b16adfa3a669c9649d3 to your computer and use it in GitHub Desktop.
This file contains 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 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