1 | ;
|
2 |
|
3 | Object.defineProperty(exports, "__esModule", {
|
4 | value: true
|
5 | });
|
6 | exports.createMap = void 0;
|
7 |
|
8 | var _function = require("../../utils/function.js");
|
9 |
|
10 | var _factory = require("../../utils/factory.js");
|
11 |
|
12 | var name = 'map';
|
13 | var dependencies = ['typed'];
|
14 | var createMap = /* #__PURE__ */(0, _factory.factory)(name, dependencies, function (_ref) {
|
15 | var typed = _ref.typed;
|
16 |
|
17 | /**
|
18 | * Create a new matrix or array with the results of the callback function executed on
|
19 | * each entry of the matrix/array.
|
20 | *
|
21 | * Syntax:
|
22 | *
|
23 | * math.map(x, callback)
|
24 | *
|
25 | * Examples:
|
26 | *
|
27 | * math.map([1, 2, 3], function(value) {
|
28 | * return value * value
|
29 | * }) // returns [1, 4, 9]
|
30 | *
|
31 | * See also:
|
32 | *
|
33 | * filter, forEach, sort
|
34 | *
|
35 | * @param {Matrix | Array} x The matrix to iterate on.
|
36 | * @param {Function} callback The callback method is invoked with three
|
37 | * parameters: the value of the element, the index
|
38 | * of the element, and the matrix being traversed.
|
39 | * @return {Matrix | array} Transformed map of x
|
40 | */
|
41 | return typed(name, {
|
42 | 'Array, function': _map,
|
43 | 'Matrix, function': function MatrixFunction(x, callback) {
|
44 | return x.map(callback);
|
45 | }
|
46 | });
|
47 | });
|
48 | /**
|
49 | * Map for a multi dimensional array
|
50 | * @param {Array} array
|
51 | * @param {Function} callback
|
52 | * @return {Array}
|
53 | * @private
|
54 | */
|
55 |
|
56 | exports.createMap = createMap;
|
57 |
|
58 | function _map(array, callback) {
|
59 | // figure out what number of arguments the callback function expects
|
60 | var args = (0, _function.maxArgumentCount)(callback);
|
61 |
|
62 | var recurse = function recurse(value, index) {
|
63 | if (Array.isArray(value)) {
|
64 | return value.map(function (child, i) {
|
65 | // we create a copy of the index array and append the new index value
|
66 | return recurse(child, index.concat(i));
|
67 | });
|
68 | } else {
|
69 | // invoke the callback function with the right number of arguments
|
70 | if (args === 1) {
|
71 | return callback(value);
|
72 | } else if (args === 2) {
|
73 | return callback(value, index);
|
74 | } else {
|
75 | // 3 or -1
|
76 | return callback(value, index, array);
|
77 | }
|
78 | }
|
79 | };
|
80 |
|
81 | return recurse(array, []);
|
82 | } |
\ | No newline at end of file |