mirror of
https://github.com/josdejong/mathjs.git
synced 2025-12-08 19:46:04 +00:00
44 lines
1.3 KiB
JavaScript
44 lines
1.3 KiB
JavaScript
module.exports = function (math) {
|
|
var isMatrix = require('../../type/Matrix').isMatrix
|
|
|
|
/**
|
|
* Create a new matrix or array with the results of the callback function executed on
|
|
* each entry of the matrix/array.
|
|
* @param {Matrix/array} The container to iterate on.
|
|
* @param {function} callback The callback method is invoked with three
|
|
* parameters: the value of the element, the index
|
|
* of the element, and the Matrix being traversed.
|
|
* @return {Matrix/array} container
|
|
*/
|
|
math.map = function (x, callback) {
|
|
if (arguments.length != 2) {
|
|
throw new util.error.ArgumentsError('map', arguments.length, 1);
|
|
}
|
|
|
|
if (Array.isArray(x)) {
|
|
return _mapArray(x, callback);
|
|
} else if (isMatrix(x)) {
|
|
return x.map(callback);
|
|
} else {
|
|
throw new UnsupportedTypeError(map, x);
|
|
}
|
|
};
|
|
|
|
function _mapArray (arrayIn, callback) {
|
|
var index = [];
|
|
var recurse = function (value, dim) {
|
|
if (Array.isArray(value)) {
|
|
return value.map(function (child, i) {
|
|
index[dim] = i;
|
|
return recurse(child, dim + 1);
|
|
});
|
|
}
|
|
else {
|
|
return callback(value, index, arrayIn);
|
|
}
|
|
};
|
|
|
|
return recurse(arrayIn, 0);
|
|
};
|
|
};
|