Skip to content

Instantly share code, notes, and snippets.

@derekstavis
Created November 28, 2018 19:53
Show Gist options
  • Save derekstavis/1193602240fe6faa4a08ea4166ccade2 to your computer and use it in GitHub Desktop.
Save derekstavis/1193602240fe6faa4a08ea4166ccade2 to your computer and use it in GitHub Desktop.
Speak numbers in Portuguese
module.exports = (function () {
var R = require('ramda');
var factor = R.curry(function (place, value) {
var int = parseInt(value / place) * place
, dec = parseInt(value % place);
return [
int == 100 && dec > 0 ? 'centoe' : R.toString(int),
int != 100 && dec > 0 ? 'and' : [],
spell(place / 10, dec)
];
});
var spell = function (place, value) {
if (value == 0) return [];
if (place == 1) return R.toString(value);
return R.cond([
// There are special sounds from 1 to 19
[R.contains(R.__, R.range(1, 20)), R.toString],
[R.modulo(R.__, place) , factor(place)],
[R.T , R.toString]
])(value);
};
var spellAmount = R.cond([
[v => v / 1000 >= 1, R.partial(spell, [1000])],
[v => v / 100 >= 1 , R.partial(spell, [100])],
[v => v / 10 >= 1 , R.partial(spell, [10])],
[R.T , R.partial(spell, [1])]
]);
var integer = function (value) {
return Math.floor(value);
};
var decimal = function (value) {
return parseInt(value.toFixed(2).split('.')[1]);
};
var spellCurrency = function (value) {
var int = integer(value)
, dec = decimal(value);
return R.flatten([
spellAmount(int),
int > 0 ? int > 1
? 'currency-integer-plural'
: 'currency-integer-singular'
: [],
dec > 0 && int > 0 ? 'and' : [],
dec > 0 ? [spellAmount(dec),
dec > 1 ? 'currency-decimal-plural'
: 'currency-decimal-singular']
: []
]);
};
var spellNumber = function (value) {
var integer = parseInt(value.toFixed(0))
, decimal = parseInt(value.toFixed(2).split('.')[1]);
return R.flatten([
spellAmount(integer),
decimal > 0 ? ['and', spellAmount(decimal)] : []
]);
};
var spellTime = function (datetime) {
var hours = datetime.hours()
, minutes = datetime.minutes();
return R.flatten([
spellNumber(hours), 'hours',
minutes > 0 ? ['and', spellNumber(minutes),
minutes > 1 ? 'minutes'
: 'minute']
: []
]);
}
return { spellCurrency: spellCurrency
, spellNumber: spellNumber
, spellTime: spellTime };
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment