In JavaScript there aren't operators defined that work on arrays, however, you can imitate their results:
Operations
List concatenation (+
)
This is very simple as there is the Array#concat()
method
a = [1, 2]
b = [3]
c = a + b
in JavaScript is equal to
const a = [1, 2];
const b = [3];
const c = a.concat(b);
console.log(c);
You could define a function that concatenates any amount of elements as:
const add = (...items) => [].concat(...items);
console.log("[1, 2] + [3]:", add([1, 2], [3]));
console.log("[1] + [2] + 3:", add([1], [2], 3));
console.log("[1, 2] + 3:", add([1, 2], 3));
console.log("1 + 2 + 3:", add(1, 2, 3));
List Repetition (*
)
There is no native way to repeat an array in JavaScript. You can apply a loop and repeatedly call add
, however an easier way might be to use Array.from
. The first argument it takes is an array-like which can be used to define the size of the create {length: neededSize}
and the second argument it takes is a function that will determine the contents of this array.
This is a simple implementation:
const mul = (arr, times) =>
Array.from({length: times*arr.length}, (_,i) => arr[i%arr.length]);
console.log("[] * 3:", mul([], 3));
console.log("[1] * 3:", mul([1], 3));
console.log("[1, 2] * 3:", mul([1, 2], 3));
console.log("[1, 2, 3] * 3:", mul([1, 2, 3], 3));
Module that handles operations fluently
For the sake of it, here is a small module that makes the operations into a fluent interface and eagerly evaluates each operations:
const add = (...items) =>
[].concat(...items);
const mul = (arr, times) =>
Array.from({length: times*arr.length}, (_,i) => arr[i%arr.length]);
const arrayMath = arr => ({
add: (...items) => arrayMath(add(arr, ...items)),
mul: num => arrayMath(mul(arr, num)),
result: () => arr
})
const res1 = arrayMath([])
.add([1, 2])
.add([3])
.mul(2)
.result();
const res2 = arrayMath([])
.add(1, 2)
.add([3])
.mul(2)
.result();
const res3 = arrayMath([])
.add(1, [2])
.add([3])
.mul(2)
.result();
const res4 = arrayMath([1])
.mul(2)
.add(2)
.mul(3)
.result();
console.log(res1);
console.log(res2);
console.log(res3);
console.log(res4);