1 |
|
2 | Promise = require 'bluebird'
|
3 |
|
4 | exports.isBrowser = () ->
|
5 | if typeof process isnt 'undefined' and process.execPath and process.execPath.match /node|iojs/
|
6 | return false
|
7 | return true
|
8 |
|
9 | exports.randomString = (n) ->
|
10 | text = "";
|
11 | possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
12 | for i in [0...n]
|
13 | idx = Math.floor Math.random()*possible.length
|
14 | text += possible.charAt idx
|
15 | return text
|
16 |
|
17 | exports.asyncSeries = (items, func, callback) ->
|
18 | items = items.slice 0
|
19 | results = []
|
20 | next = () ->
|
21 | if items.length == 0
|
22 | return callback null, results
|
23 | item = items.shift()
|
24 | func item, (err, result) ->
|
25 | return callback err if err
|
26 | results.push result
|
27 | return next()
|
28 | next()
|
29 |
|
30 | exports.isArray = Array.isArray || ( value ) -> return {}.toString.call( value ) is '[object Array]'
|
31 |
|
32 | exports.startsWith = (str, sub) ->
|
33 | return str.indexOf(sub) == 0
|
34 |
|
35 |
|
36 | rejectDelayer = (delay) ->
|
37 | f = (reason) ->
|
38 | return new Promise (resolve, reject) ->
|
39 | setTimeout(reject.bind(null, reason), delay)
|
40 | return f
|
41 |
|
42 | exports.retryUntil = (attempt, test, delay=500, max=5) ->
|
43 | p = Promise.reject(new Error 'retry starter')
|
44 | for i in [0..max]
|
45 | p = p.catch(attempt).then(test).catch(rejectDelayer(delay))
|
46 | return p
|