UNPKG

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