-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy patharrayFilterWithIndex.js
45 lines (43 loc) · 1.26 KB
/
arrayFilterWithIndex.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
38
39
40
41
42
43
44
45
const curry4 = require('./curry4')
const __ = require('./placeholder')
const isPromise = require('./isPromise')
const promiseAll = require('./promiseAll')
const arrayExtendMapWithIndex = require('./arrayExtendMapWithIndex')
const arrayFilterByConditions = require('./arrayFilterByConditions')
/**
* @name arrayFilterWithIndex
*
* @synopsis
* ```coffeescript [specscript]
* arrayFilterWithIndex<
* T any,
* array Array<T>,
* index number,
* indexedPredicate (T, index, array)=>Promise|boolean,
* >(array, indexedPredicate) -> filteredWithIndex Array<T>
* ```
*
* @description
* Filter an array concurrently by predicate.
*/
const arrayFilterWithIndex = function (array, predicate) {
const arrayLength = array.length,
result = []
let index = -1,
resultIndex = -1
while (++index < arrayLength) {
const item = array[index],
shouldIncludeItem = predicate(item, index, array)
if (isPromise(shouldIncludeItem)) {
return promiseAll(
arrayExtendMapWithIndex(
[shouldIncludeItem], array, predicate, index)).then(
curry4(arrayFilterByConditions, array, result, index - 1, __))
}
if (shouldIncludeItem) {
result[++resultIndex] = item
}
}
return result
}
module.exports = arrayFilterWithIndex