Skip to content

Instantly share code, notes, and snippets.

@robkuz
Created August 9, 2012 14:56
Show Gist options
  • Select an option

  • Save robkuz/3304920 to your computer and use it in GitHub Desktop.

Select an option

Save robkuz/3304920 to your computer and use it in GitHub Desktop.
DIY Enums & tests
#take care I am using requirejs for modules
define [], ->
Enum = (enumeration)->
check = (value)->
newval = null
for key, val of enumeration
if val == value
newval = value
break
if !newval
throw "Invalid Enum Value: #{value}"
result = (init)->
state = init.call(enumeration)
check state
result_enum = (callback)->
value = callback.call(enumeration)
if value == null or value == undefined
return state
else
check value
state = value
#needed to create a closure for v
isfn = (v)-> -> state == v
#add a isVALUE - fn for every key
for k, v of enumeration
result_enum["is" + k] = isfn v
#return the name of the actual value
result_enum.key = ->
for k,v of enumeration
if v == state
return k
result_enum
for key, value of enumeration
result[key] = value
result
return Enum
#take care requirejs modules and jasmine
define [
"some/path/to/enum"
],
(Enum)->
describe "enum/", ->
#define enumeration
httpcodes = Enum
OK: 200
BADREQUEST: 400
UNAUTHORIZED: 401
SERVER_ERROR: 500
chrome = httpcodes -> @SERVER_ERROR
firefox = httpcodes -> @SERVER_ERROR
safari = httpcodes -> @SERVER_ERROR
it "is properly initialized", ->
expect(chrome ->).toEqual(httpcodes.SERVER_ERROR)
expect(safari ->).toEqual(httpcodes.SERVER_ERROR)
expect(firefox ->).toEqual(httpcodes.SERVER_ERROR)
it "can set other values", ->
chrome -> @OK
firefox -> @BADREQUEST
safari -> @UNAUTHORIZED
expect(chrome ->).toEqual httpcodes.OK
expect(safari ->).toEqual httpcodes.UNAUTHORIZED
expect(firefox ->).toEqual httpcodes.BADREQUEST
it "can compare values", ->
expect((chrome ->) == httpcodes.OK).toBeTruthy()
it "can compare values with is functions", ->
debugger
expect(chrome.isOK()).toBeTruthy()
expect(chrome.isBADREQUEST()).toBeFalsy()
expect(safari.isOK()).toBeFalsy()
expect(safari.isUNAUTHORIZED()).toBeTruthy()
expect(firefox.isOK()).toBeFalsy()
expect(firefox.isBADREQUEST()).toBeTruthy()
it "fails with invalid value", ->
#expect(safari -> 999).toThrow("Invalid Enum Value: 999")
try
safari -> 999
catch err
expect(err).toEqual("Invalid Enum Value: 999")
it "returns the key (name)", ->
expect(chrome.key()).toEqual("OK")
expect(firefox.key()).toEqual("BADREQUEST")
expect(safari.key()).toEqual("UNAUTHORIZED")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment