UNPKG

1.34 kBtext/coffeescriptView Raw
1{curry} = require "fairmont-core"
2{Method} = require "fairmont-multimethods"
3{isFunction, isGenerator} = require "./type"
4{promise, async} = require "./promise"
5{isArray, isString, isObject} = require "./type"
6{blank} = require "./string"
7
8# TODO: move to core
9memoize = do (_hash = undefined) ->
10 _hash = (x) -> x.toString()
11 (fn, hash = _hash, memo = {}) ->
12 (x) -> memo[hash x] ?= fn x
13
14timer = (wait, action) ->
15 id = setTimeout(action, wait)
16 -> clearTimeout( id )
17
18sleep = (interval) ->
19 promise (resolve, reject) ->
20 timer interval, -> resolve()
21
22times = curry (fn, n) -> fn() until n-- == 0
23
24benchmark = Method.create()
25
26Method.define benchmark, isFunction, (fn) ->
27 start = Date.now()
28 fn()
29 Date.now() - start
30
31Method.define benchmark, isGenerator, (fn) ->
32 start = Date.now()
33 yield fn()
34 Date.now() - start
35
36# empty and length work on both arrays and strings
37# and really anything with a meaningful length
38# attribute, so that's why they're here and not
39# in array...
40
41# TODO: multimethod variant of empty that allows
42# empty to be defined for any type
43
44empty = (x) -> x.length == 0
45length = (x) -> x.length
46
47assert = require "assert"
48deepEqual = (a, b) ->
49 try
50 assert.deepEqual a, b
51 true
52 catch
53 false
54
55module.exports = {times, sleep, timer, memoize,
56 times, benchmark, empty, length, deepEqual}