UNPKG

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