All of the documentation for creating sub-arrays I've seen talks about slice
, which creates a copy of the array. I'm wondering if it's possible to create a slice of an array without copying, so that modifying the slice modifies the original array. For example:
var foo = [1, 2, 3, 4, 5];
var bar = foo.subarray(2, 4);
console.log(bar); // [2, 3, 4]
bar[0] = 'hello, world';
console.log(bar); // ['hello, world', 3, 4]
console.log(foo); // [1, 'hello, world', 3, 4, 5]
Unfortunately, @Derek's answer takes O(n)
to create a subarray of length n
, whereas we can do it in O(1)
if we access values with subarray.get(i)
instead of subarry[i]
:
function make_subarray (array, from, to) {
return {
get: function (i) {
return array[i+from]
},
length: to - from
}
}
You would use this like:
for (var i=0; i<subarray.length; i++) {
subarray.get(i)
}
Or you can add a map()
function to the subarray
definition:
function make_subarray (array, from, to) {
return {
...
map: function (f) {
for (var i=0; i<this.length; i++)
f(this.get(i))
}
...
}
}
Each call to Object.defineProperty(...{get: ...})
in Derek's answer is slow in modern browsers, so it's good to avoid doing a lot of them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With