Skip to content

Instantly share code, notes, and snippets.

@cj
Created August 25, 2011 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cj/1170941 to your computer and use it in GitHub Desktop.
Save cj/1170941 to your computer and use it in GitHub Desktop.
converted some underscore methods to coffeescript
# Returns only the objects that the callback returns true to
# replaces the underscore _.select method
filter = (obj, callback) ->
element for element in obj when callback(element)
# Deep clones an object, replaces underscores _.clone method
clone = (obj) ->
if not obj? or typeof obj isnt 'object'
return obj
newInstance = new obj.constructor()
for key of obj
newInstance[key] = clone obj[key]
newInstance
# Replaces underscores _.isEmpty function
empty = (obj) ->
(return false for own prop of obj)
true
# Replaces underscores _.extend function
extend = (object, extenders...) ->
return {} if not object?
for other in extenders
for own key, val of other
if not object[key]? or typeof val isnt "object"
object[key] = val
else
object[key] = extend object[key], val
object
###
flat_array= ['foo', 'bar', 'moo', 'cow']
Output:
foo:
bar:
moo: 'cow'
###
make_multi= (flat_array, obj= {}) ->
if not flat_array.length then return {}
if flat_array.length == 1 then flat_array[0] else
result = {}
result[flat_array[0]] = make_multi(flat_array[1..])
return result
# isNumber ('123'); // true
# isNumber (5); // true
# isNumber ('q345'); // false
isNumber= (o) ->
not isNaN(o-0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment