Last active
August 2, 2016 05:41
-
-
Save alanrsoares/e1961f0e9b5f5fc5a39c7cdd4de8375e to your computer and use it in GitHub Desktop.
Agnostic, extensible and composable set of functions for formatting numbers to currency
This file contains hidden or 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
// :: delimitGroups = (number, string) => string => string | |
const delimitGroups = (groupSize, delimiter) => s => | |
s.split('') | |
.reduceRight((acc, x, i) => | |
`${x}${(s.length - 1 - i) % groupSize ? '' : delimiter}${acc}`) | |
// :: format = number => object => string | |
export const format = options => n => | |
(([left, right]) => | |
`${options.symbol}${ | |
delimitGroups(options.groupSize, options.groupSeparator)(left) | |
}${options.decimalSeparator}${right}` | |
)(n.toFixed(options.decimals).split('.')) | |
// :: formatWithOptions = object => (number, object) => string | |
export const formatWithOptions = options => (n, overrides = {}) => | |
format({ | |
...options, | |
...overrides | |
})(n) | |
// USAGE | |
// configs | |
const currencyLocale = { | |
NZD: { | |
symbol: '$', | |
groupSize: 3, | |
groupSeparator: ',', | |
decimalSeparator: '.', | |
decimals: 2 | |
}, | |
BRL: { | |
symbol: 'R$', | |
groupSize: 3, | |
groupSeparator: '.', | |
decimalSeparator: ',', | |
decimals: 2 | |
} | |
} | |
// high level localized wrappers | |
const formatNZD = formatCurrencyWithOptions(currencyLocale.NZD) | |
const formatBRL = formatCurrencyWithOptions(currencyLocale.BRL) | |
console.log( | |
formatNZD(2.32), // $2.32 | |
formatNZD(11231232.324567, { decimals: 4, symbol: '' }), // 11,231,232.3246 | |
formatBRL(32135.35267) // R$32.135,35 | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment