Skip to content

Instantly share code, notes, and snippets.

@kerrishotts
Last active July 20, 2019 05:25
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 kerrishotts/ea2bd99b0b874f7e17042b506f920377 to your computer and use it in GitHub Desktop.
Save kerrishotts/ea2bd99b0b874f7e17042b506f920377 to your computer and use it in GitHub Desktop.
2019-07-19 Dev.to challenge
function numToText(n) {
if (n < 1 || n > 999 || n === undefined) {
throw new Error(`arg must be > 0 and < 1000`);
}
const ones = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
const prefixes = ["thir", "four", "fif", "six", "seven", "eigh", "nine"];
const tys = ["", "", "twenty", ...prefixes.map(prefix => `${prefix}ty`)];
tys[4] = "forty";
const oneTeens = [...ones, "ten", "eleven", "twelve", ...prefixes.map(prefix => `${prefix}teen`)];
const parts = [];
let rem = n;
if (rem >= 100) {
parts.push(ones[Math.floor(rem / 100)], "hundred")
rem = rem % 100;
}
if (rem >= 20) {
parts.push(tys[Math.floor(rem / 10)]);
rem = rem % 10;
}
if (rem > 0 && rem < 20) {
parts.push(oneTeens[rem]);
}
return parts.join(" ");
}
const testCases = [
{ args: [ 1 ], result: "one" },
{ args: [ 10 ], result: "ten" },
{ args: [ 12 ], result: "twelve" },
{ args: [ 14 ], result: "fourteen" },
{ args: [ 50 ], result: "fifty" },
{ args: [ 57 ], result: "fifty seven" },
{ args: [ 93 ], result: "ninety three" },
{ args: [ 100 ], result: "one hundred" },
{ args: [ 105 ], result: "one hundred five" },
{ args: [ 123 ], result: "one hundred twenty three" },
{ args: [ 111 ], result: "one hundred eleven" },
{ args: [ 114 ], result: "one hundred fourteen" },
{ args: [ 141 ], result: "one hundred forty one" },
{ args: [ 193 ], result: "one hundred ninety three" },
{ args: [ 200 ], result: "two hundred" },
{ args: [ 222 ], result: "two hundred twenty two" },
{ args: [ 333 ], result: "three hundred thirty three" },
{ args: [ 347 ], result: "three hundred forty seven" },
{ args: [ 444 ], result: "four hundred forty four" },
{ args: [ 555 ], result: "five hundred fifty five" },
{ args: [ 666 ], result: "six hundred sixty six" },
{ args: [ 777 ], result: "seven hundred seventy seven" },
{ args: [ 888 ], result: "eight hundred eighty eight" },
{ args: [ 900 ], result: "nine hundred" },
{ args: [ 930 ], result: "nine hundred thirty" },
{ args: [ 999 ], result: "nine hundred ninety nine" },
];
const testAllCases = (fn, cases) =>
cases.map(({args, result}) => [`${args} -> ${result}`, fn(...args) === result])
.filter(([_, pass]) => !pass);
const failures = testAllCases(numToText, testCases);
if (failures.length > 0) {
throw new Error(JSON.stringify(failures), 2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment