Skip to content

Instantly share code, notes, and snippets.

@kanzure
Last active December 17, 2015 20:09
Show Gist options
  • Save kanzure/5665585 to your computer and use it in GitHub Desktop.
Save kanzure/5665585 to your computer and use it in GitHub Desktop.
zeropad.coffee
exports.run = ->
describe("utils.zeroPad", ->
zeroPad = utils.zeroPad
it("should have zeroPad", ->
should.exist(utils.zeroPad)
should.exist(zeroPad)
)
it("should be a function", ->
expect(typeof(zeroPad)).to.equal("function")
)
it("should not pad 1 digit", ->
input = 1
expect(zeroPad(input, 1)).to.equal("1")
)
it("should pad to 2 digits", ->
input = 2
expect(zeroPad(input, 2)).to.equal("02")
)
it("should pad to 3 digits", ->
input = 57
expect(zeroPad(input, 3)).to.equal("057")
)
it("should pad to 4 digits", ->
input = 81
expect(zeroPad(input, 4)).to.equal("0081")
)
it("should pad to 10 digits", ->
input = 1
expect(zeroPad(input, 10)).to.equal("0000000001")
)
)
zeroPad = (num, numZeros) ->
n = Math.abs(num)
zeros = Math.max(0, numZeros - Math.floor(n).toString().length)
zeroString = Math.pow(10, zeros).toString().substr(1)
if num < 0
zeroString = "-" + zeroString
zeroString + n
exports.zeroPad = zeroPad
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment