Skip to content

Instantly share code, notes, and snippets.

@lamchau
Last active June 14, 2018 05:42
Show Gist options
  • Save lamchau/259183f994b85447b522ddb48652d90f to your computer and use it in GitHub Desktop.
Save lamchau/259183f994b85447b522ddb48652d90f to your computer and use it in GitHub Desktop.
const WORDS_MAP = Object.freeze({
0: 'zero',
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
16: 'sixteen',
17: 'seventeen',
18: 'eighteen',
19: 'nineteen',
20: 'twenty',
30: 'thirty',
40: 'forty',
50: 'fifty',
60: 'sixty',
70: 'seventy',
80: 'eighty',
90: 'ninety',
});
const LARGE_MAP = Object.freeze([
[1e9, 'billion'],
[1e6, 'million'],
[1e3, 'thousand']
]);
function asWords(n) {
const isInteger = typeof n === 'number';
if (!isInteger) {
return null;
}
let value = n;
const str = [];
if (value === 0) {
return WORDS_MAP[value];
}
LARGE_MAP.forEach(([key, suffix]) => {
if (value >= key) {
str.push(getPrefix(value / key), suffix);
value %= key;
}
});
if (value > 0) {
str.push(getPrefix(value));
}
return str.join(' ').trim();
}
function getPrefix(n) {
const str = [];
let truncated = Math.trunc(n);
if (truncated >= 100) {
const key = Math.trunc(truncated / 100);
str.push(WORDS_MAP[key], 'hundred');
truncated %= 100;
}
if (truncated > 0) {
if (truncated <= 20) {
str.push(WORDS_MAP[truncated]);
} else {
const key = Math.trunc(truncated / 10) * 10;
str.push(WORDS_MAP[key]);
const ones = truncated % 10;
if (ones > 0) {
str.push(WORDS_MAP[ones]);
}
}
}
return str.join(' ').trim();
}
function test(input, expected) {
const actual = asWords(input);
if (actual === expected) {
console.log(`[ ok]: ${actual} === ${expected}`);
} else {
console.log(`[fail]: ${actual} !== ${expected}`);
}
}
test(null, null);
test(0, 'zero');
test(1, 'one');
test(2, 'two');
test(9, 'nine');
test(10, 'ten');
test(20, 'twenty');
test(120, 'one hundred twenty');
test(999, 'nine hundred ninety nine');
test(899, 'eight hundred ninety nine');
test(1e3, 'one thousand');
test(1e4, 'ten thousand');
test(100000, 'one hundred thousand');
test(1e6, 'one million');
test(1e7, 'ten million');
test(123456789, 'one hundred twenty three million four hundred fifty six thousand seven hundred eighty nine');
test(123456000, 'one hundred twenty three million four hundred fifty six thousand');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment