A micro JS library (254 bytes) for matrix operations.
This library is intended for use in environments where the available storage space is very limited; like blockchains for example. Everything is stripped down to the bare essentials.
Perform operations on two matrices with equal dimensions. For example, If you'd want to do a add operation:
let a = [
[1, 2, 3],
[0, 1, 0]
]
let b = [
[3, 2, 1],
[1, 0, 1]
]
Mtx.op(a, b, (x, y) => x + y)
// => [
// [4, 4, 4],
// [1, 1, 1]
// ]
Passing a numeric value as the second argument will create a uniform matrix of equal dimensions as the one passed as the first argument, before performing the operation:
Mtx.op(a, 2, (x, y) => x + y)
// => [
// [3, 4, 5],
// [2, 3, 2]
// ]
Alternatively, a single matrix row can be passed as the second argument, which will be used to build a veritcally uniform matrix before performing the operation:
Mtx.op(a, [1, 11, 1], (x, y) => x + y)
// => [
// [2, 13, 4],
// [1, 12, 1]
// ]
Often you'll need to repeat the same matrix operation multiple times. That's where common operations come in.
First, register your favourite operation:
Mtx.co['+'] = (x, y) => x + y
Then use and re-use that operation wherever needed:
Mtx.op(a, b, Mtx.co['+'])
With the fill
method, a new matrix can be created with a given number of rows
and columns:
Mtx.fill(3, 4)
// => [
// [0, 0, 0, 0],
// [0, 0, 0, 0],
// [0, 0, 0, 0]
// ]
Optionally, an initial value can be passed as the third argument:
Mtx.fill(3, 4, 2)
// => [
// [2, 2, 2, 2],
// [2, 2, 2, 2],
// [2, 2, 2, 2]
// ]
Alternatively, a full row with columns can be passed instead of the number of columns, to create a matrix with uniform columns:
Mtx.fill(3, [0, 1, 0])
// => [
// [0, 1, 0],
// [0, 1, 0],
// [0, 1, 0]
// ]
matrix.onchain.js is licensed under the terms of the MIT License.