-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
37 lines (31 loc) · 894 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
const debug = require('debug')('then-while')
const Promise = require('any-promise')
const isPromise = require('is-promise')
function asPromise (value) {
return isPromise(value) ? value : Promise.resolve(value)
}
function test (predicateFn) {
return value => {
return asPromise(predicateFn(value)).then(shouldContinue => ({
shouldContinue,
value
}))
}
}
function repeatOrFulfill (performStep) {
return ({ shouldContinue, value }) => {
debug(
`The step function generated ${value} which was tested as ${shouldContinue}.`
)
return shouldContinue ? performStep() : value
}
}
function createThenWhile (predicateFn, stepFn) {
function thenWhile (...args) {
return asPromise(stepFn(...args))
.then(test(predicateFn))
.then(repeatOrFulfill(thenWhile.bind(null, ...args)))
}
return thenWhile
}
module.exports = createThenWhile