Created
August 25, 2011 15:35
-
-
Save cj/1170941 to your computer and use it in GitHub Desktop.
converted some underscore methods to coffeescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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