UNPKG

2.26 kBJavaScriptView Raw
1import { filter, filterRegExp } from '../../utils/array'
2import { maxArgumentCount } from '../../utils/function'
3import { factory } from '../../utils/factory'
4
5const name = 'filter'
6const dependencies = ['typed']
7
8export const createFilter = /* #__PURE__ */ factory(name, dependencies, ({ typed }) => {
9 /**
10 * Filter the items in an array or one dimensional matrix.
11 *
12 * Syntax:
13 *
14 * math.filter(x, test)
15 *
16 * Examples:
17 *
18 * function isPositive (x) {
19 * return x > 0
20 * }
21 * math.filter([6, -2, -1, 4, 3], isPositive) // returns [6, 4, 3]
22 *
23 * math.filter(["23", "foo", "100", "55", "bar"], /[0-9]+/) // returns ["23", "100", "55"]
24 *
25 * See also:
26 *
27 * forEach, map, sort
28 *
29 * @param {Matrix | Array} x A one dimensional matrix or array to filter
30 * @param {Function | RegExp} test
31 * A function or regular expression to test items.
32 * All entries for which `test` returns true are returned.
33 * When `test` is a function, it is invoked with three parameters:
34 * the value of the element, the index of the element, and the
35 * matrix/array being traversed. The function must return a boolean.
36 * @return {Matrix | Array} Returns the filtered matrix.
37 */
38 return typed('filter', {
39 'Array, function': _filterCallback,
40
41 'Matrix, function': function (x, test) {
42 return x.create(_filterCallback(x.toArray(), test))
43 },
44
45 'Array, RegExp': filterRegExp,
46
47 'Matrix, RegExp': function (x, test) {
48 return x.create(filterRegExp(x.toArray(), test))
49 }
50 })
51})
52
53/**
54 * Filter values in a callback given a callback function
55 * @param {Array} x
56 * @param {Function} callback
57 * @return {Array} Returns the filtered array
58 * @private
59 */
60function _filterCallback (x, callback) {
61 // figure out what number of arguments the callback function expects
62 const args = maxArgumentCount(callback)
63
64 return filter(x, function (value, index, array) {
65 // invoke the callback function with the right number of arguments
66 if (args === 1) {
67 return callback(value)
68 } else if (args === 2) {
69 return callback(value, [index])
70 } else { // 3 or -1
71 return callback(value, [index], array)
72 }
73 })
74}