UNPKG

2.5 kBJavaScriptView Raw
1import { isFunctionAssignmentNode, isSymbolNode } from '../../utils/is.js';
2import { filter, filterRegExp } from '../../utils/array.js';
3import { maxArgumentCount } from '../../utils/function.js';
4import { compileInlineExpression } from './utils/compileInlineExpression.js';
5import { factory } from '../../utils/factory.js';
6var name = 'filter';
7var dependencies = ['typed'];
8export var createFilterTransform = /* #__PURE__ */factory(name, dependencies, (_ref) => {
9 var {
10 typed
11 } = _ref;
12
13 /**
14 * Attach a transform function to math.filter
15 * Adds a property transform containing the transform function.
16 *
17 * This transform adds support for equations as test function for math.filter,
18 * so you can do something like 'filter([3, -2, 5], x > 0)'.
19 */
20 function filterTransform(args, math, scope) {
21 var x, callback;
22
23 if (args[0]) {
24 x = args[0].compile().evaluate(scope);
25 }
26
27 if (args[1]) {
28 if (isSymbolNode(args[1]) || isFunctionAssignmentNode(args[1])) {
29 // a function pointer, like filter([3, -2, 5], myTestFunction)
30 callback = args[1].compile().evaluate(scope);
31 } else {
32 // an expression like filter([3, -2, 5], x > 0)
33 callback = compileInlineExpression(args[1], math, scope);
34 }
35 }
36
37 return filter(x, callback);
38 }
39
40 filterTransform.rawArgs = true; // one based version of function filter
41
42 var filter = typed('filter', {
43 'Array, function': _filter,
44 'Matrix, function': function MatrixFunction(x, test) {
45 return x.create(_filter(x.toArray(), test));
46 },
47 'Array, RegExp': filterRegExp,
48 'Matrix, RegExp': function MatrixRegExp(x, test) {
49 return x.create(filterRegExp(x.toArray(), test));
50 }
51 });
52 return filterTransform;
53}, {
54 isTransformFunction: true
55});
56/**
57 * Filter values in a callback given a callback function
58 *
59 * !!! Passes a one-based index !!!
60 *
61 * @param {Array} x
62 * @param {Function} callback
63 * @return {Array} Returns the filtered array
64 * @private
65 */
66
67function _filter(x, callback) {
68 // figure out what number of arguments the callback function expects
69 var args = maxArgumentCount(callback);
70 return filter(x, function (value, index, array) {
71 // invoke the callback function with the right number of arguments
72 if (args === 1) {
73 return callback(value);
74 } else if (args === 2) {
75 return callback(value, [index + 1]);
76 } else {
77 // 3 or -1
78 return callback(value, [index + 1], array);
79 }
80 });
81}
\No newline at end of file