Book Image

CoffeeScript Application Development Cookbook

By : Mike Hatfield
Book Image

CoffeeScript Application Development Cookbook

By: Mike Hatfield

Overview of this book

Table of Contents (18 chapters)
CoffeeScript Application Development Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Working with numbers


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.

Converting between bases

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.

How to do it...

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...