This section looks at various aspects of working with numbers in CoffeeScript. All of this functionality comes from JavaScript but is made better by using CoffeeScript.
JavaScript provides a parseInt()
function that is most commonly used to convert strings to numeric values but it can also be used to convert numbers between bases in the range of base 2 to base 32. This section demonstrates converting numbers to and from base 10.
Let's define several base conversion methods in a utility module that we can use in our applications:
convertBase = (number, fromBase, toBase) -> value = parseInt number, fromBase value.toString toBase convertToBase2 = (number, fromBase = 10) -> convertBase number, fromBase, 2 convertToBase10 = (number, fromBase = 2) -> convertBase number, fromBase, 10 convertToBase16 = (number, fromBase = 10) -> convertBase number, fromBase, 16 module.exports = convertBase: convertBase convertToBase2...