util.coffee | |
---|---|
exports.extend = extend = (x, more...) ->
for o in more
x[k] = v for k,v of o
x
exports.bind = bind = (fn, self, args...) ->
if not fn? then throw "Cannot bind null"
if isFunction fn
(args2...) -> fn.apply self, args.concat args2
else # (self, method1, method2...)
methods = [self].concat args
self = fn
for m in methods
self[m] = bind self[m], self
exports.contains = (x, val) ->
if not x? then return false
if not isString x then x = toArray(x)
x.indexOf(val) >= 0
exports.remove = remove = (x, vals...) ->
if isArray x
y for y in x when not (y in vals)
exports.without = without = remove
exports.keys = (x) -> k for k of x
exports.last = (arr, val) -> arr[arr.length - 1]
exports.isHash = isHash = (o) -> o?.constructor.name is 'Object'
exports.isPlainObject = isHash
exports.isFunction = isFunction = (x) -> !!(x and x.constructor and x.call and x.apply)
exports.isString = isString = (x) -> !!(x is '' or (x and x.charCodeAt and x.substr))
exports.isText = (x) -> x and (x.nodeType is 3 or x.tagName is "TEXT")
exports.isLeaf = (x) -> x and x.childNodes.length is 0
exports.isElement = (x) -> x and x.childNodes and x.tagName
exports.isDocument = (x) -> x and x.body and x.documentElement
exports.isNumber = (x) -> x? and x.toPrecision and x.toExponential
exports.isDate = (x) -> x and x.setUTCDate and x.getFullYear
exports.isBoolean = (x) -> x is false or x is true
exports.isArray = isArray = (x) -> x and x.slice and x.join
exports.isEmpty = isEmpty = (x) ->
if isArray x then !!x.length
else
return false for own k of x
return true | |
creates a shallow clone | exports.copy = copy = (x) ->
if isArray x then x.slice 0
else if isHash x then extend {}, x
else throw "I don't know how to copy this"
exports.escapeRegExp = (x) ->
specials = new RegExp "[.*+?|()\\[\\]{}\\\\]", "g" # .*+?|()[]{}\
x.replace specials, "\\$&"
exports.escapeHTML = (x) ->
x = x.replace '&', '&'
x = x.replace '>', '>'
x = x.replace '<', '<'
exports.toArray = toArray = (x) -> Array.prototype.slice.call x, 0
exports.Args = (signature, args) ->
out = []; args = toArray args
for test in signature
out.push if test args[0] then args.shift() else null
out.concat args
|