UNPKG

2.09 kBtext/coffeescriptView Raw
1{curry, negate} = require "fairmont-core"
2{isObject, isFunction} = require "./type"
3{deepEqual} = require "./util"
4
5include = extend = (object, mixins...) ->
6 for mixin in mixins
7 for key, value of mixin
8 object[key] = value
9 object
10
11merge = (objects...) ->
12
13 destination = {}
14 for object in objects
15 destination[k] = v for k, v of object
16 destination
17
18clone = (object) ->
19
20 if not object? or typeof object isnt 'object'
21 return object
22
23 if object instanceof Date
24 return new Date(object.getTime())
25
26 if object instanceof RegExp
27 flags = ''
28 flags += 'g' if object.global?
29 flags += 'i' if object.ignoreCase?
30 flags += 'm' if object.multiline?
31 flags += 'y' if object.sticky?
32 return new RegExp(object.source, flags)
33
34 _clone = new object.constructor()
35
36 for key of object
37 _clone[key] = (clone object[key])
38
39 return _clone
40
41property = curry (key, object) -> object[key]
42
43delegate = (from, to) ->
44
45 for name, value of to when isFunction value
46 do (value) ->
47 from[name] = (args...) -> value.call to, args...
48
49bind = curry (f, x) -> f.bind x
50
51detach = (f) -> curry (x, args...) -> f.apply x, args
52
53properties = do ->
54 defaults = enumerable: true, configurable: true
55 (object, properties) ->
56 for key, value of properties
57 include value, defaults
58 Object.defineProperty object, key, value
59
60has = curry (p, x) -> x[p]?
61
62keys = Object.keys
63
64values = (x) -> v for k, v of x
65
66pairs = (x) -> [k, v] for k, v of x
67
68pick = curry (f, x) ->
69 r = {}
70 r[k] = v for k, v of x when f k, v
71 r
72
73omit = curry (f, x) -> pick (negate f), x
74
75query = curry (example, target) ->
76 if (isObject example) && (isObject target)
77 for k, v of example
78 return false unless query v, target[k]
79 return true
80 else
81 deepEqual example, target
82
83toJSON = (x, pretty = false) ->
84 if pretty
85 JSON.stringify x, null, 2
86 else
87 JSON.stringify x
88
89fromJSON = JSON.parse
90
91module.exports = {include, extend, merge, clone,
92 properties, property, delegate, bind, detach,
93 has, keys, values, pairs, pick, omit, query,
94 toJSON, fromJSON}