From bc3cbbcb20ae9bcf40e409e4f94b901a398d633d Mon Sep 17 00:00:00 2001 From: Tom Hickson Date: Wed, 8 Apr 2020 18:55:37 +0100 Subject: [PATCH] Diff function --- src/function/matrix/diff.js | 46 +++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/function/matrix/diff.js diff --git a/src/function/matrix/diff.js b/src/function/matrix/diff.js new file mode 100644 index 000000000..1d357fe02 --- /dev/null +++ b/src/function/matrix/diff.js @@ -0,0 +1,46 @@ +import { factory } from '../../utils/factory' +import { isMatrix } from '../../utils/is' + +const name = 'diff' +const dependencies = ['typed', 'matrix'] + +export const createDiff = /* #__PURE__ */ factory(name, dependencies, ({ typed, matrix }) => { + /** + * Create a new matrix or array of the difference between elements of the given array + * + * Syntax: + * + * math.diff(x) + * + * Examples: + * + * const arr = [1, 2, 4, 7, 0] + * math.diff(arr) // returns [1, 2, 3, -7] + * + * @param {Array | Matrix } x An array or matrix + * @return {Array | Matrix} Difference between array elements + */ + return typed(name, { + 'Array | Matrix, function': function (x) { + if (isMatrix(x)) { + return matrix(_ArrayDiff(x.toArray(), diff)) + } else { + return _ArrayDiff(x) + } + } + }) + + /** + * + * @param {Array} arr An array + * @return {Array} resulting array + */ + function _ArrayDiff (arr) { + const result = [] + const size = arr.length + for (let i = 1; i < size; i++) { + result.push(arr[i] - arr[i-1]) + } + return result + } +}) \ No newline at end of file