Skip to content

Instantly share code, notes, and snippets.

@rayrutjes
Created July 28, 2016 10:12
Show Gist options
  • Save rayrutjes/98d61b470fbf5676d6f4a2730799ebd4 to your computer and use it in GitHub Desktop.
Save rayrutjes/98d61b470fbf5676d6f4a2730799ebd4 to your computer and use it in GitHub Desktop.
Generate number synonyms for Algolia. Run `node` algolia-number-synonyms.js
// @see number to string, pluginized from http://stackoverflow.com/questions/5529934/javascript-numbers-to-words
// @see http://stackoverflow.com/questions/20425771/how-to-replace-1-with-first-2-with-second-3-with-third-etc
const convert = function (num) {
return num2str.convert(num);
}
const num2str = {}
num2str.ones=['','one','two','three','four','five','six','seven','eight','nine'];
num2str.tens=['','','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety'];
num2str.teens=['ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];
num2str.convert_millions = function(num) {
if (num >= 1000000) {
return this.convert_millions(Math.floor(num / 1000000)) + " million " + this.convert_thousands(num % 1000000);
}
else {
return this.convert_thousands(num);
}
}
num2str.convert_thousands = function(num) {
if (num >= 1000) {
return this.convert_hundreds(Math.floor(num / 1000)) + " thousand " + this.convert_hundreds(num % 1000);
}
else {
return this.convert_hundreds(num);
}
}
num2str.convert_hundreds = function(num) {
if (num > 99) {
return this.ones[Math.floor(num / 100)] + " hundred " + this.convert_tens(num % 100);
}
else {
return this.convert_tens(num);
}
}
num2str.convert_tens = function(num) {
if (num < 10) return this.ones[num];
else if (num >= 10 && num < 20) return this.teens[num - 10];
else {
return this.tens[Math.floor(num / 10)] + " " + this.ones[num % 10];
}
}
num2str.convert = function(num) {
if (num == 0) return "zero";
else return this.convert_millions(num);
}
var special = ['zeroth','first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelvth', 'thirteenth', 'fourteenth', 'fifteenth', 'sixteenth', 'seventeenth', 'eighteenth', 'nineteenth'];
var deca = ['twent', 'thirt', 'fourt', 'fift', 'sixt', 'sevent', 'eight', 'ninet'];
function stringifyNumber(n) {
if (n < 20) return special[n];
if (n%10 === 0) return deca[Math.floor(n/10)-2] + 'ieth';
return deca[Math.floor(n/10)-2] + 'y-' + special[n%10];
}
var getOrdinal = function(n) {
var s=["th","st","nd","rd"],
v=n%100;
return n+(s[(v-20)%10]||s[v]||s[0]);
}
// Currently limited to 99
for (let i=1; i<=100; i++) {
console.log({
type: "synonym",
synonyms: [getOrdinal(i), stringifyNumber(i), convert(i)]
})
}
{ type: 'synonym',synonyms: [ '88th', 'eighty-eighth', 'eighty eight' ] }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment