liudong
2023-05-29 340f156319b863525e50e900c58e59b86ecb3d5e
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
46
47
48
49
50
51
52
53
54
55
56
'use strict'
var testValue = require('test-value')
 
/**
 * @module reduce-extract
 */
module.exports = extract
 
/**
Removes items from `array` which satisfy the query. Modifies the input array, returns the extracted.
 
@param {Array} - the input array, modified directly
@param {any} - if an item in the input array passes this test it is removed
@alias module:reduce-extract
@example
> DJs = [
    { name: "Trevor", sacked: true },
    { name: "Mike", sacked: true },
    { name: "Chris", sacked: false },
    { name: "Alan", sacked: false }
]
 
> a.extract(DJs, { sacked: true })
[ { name: 'Trevor', sacked: true },
  { name: 'Mike', sacked: true } ]
 
> DJs
[ { name: 'Chris', sacked: false },
  { name: 'Alan', sacked: false } ]
 
*/
function extract (query) {
  var toSplice = []
  var extracted = []
  return function (prev, curr, index, array) {
    if (prev !== extracted) {
      if (testValue(prev, query)) {
        extracted.push(prev)
        toSplice.push(index - 1)
      }
    }
 
    if (testValue(curr, query)) {
      extracted.push(curr)
      toSplice.push(index)
    }
 
    if (index === array.length - 1) {
      toSplice.reverse()
      for (var i = 0; i < toSplice.length; i++) {
        array.splice(toSplice[i], 1)
      }
    }
    return extracted
  }
}