Presenting a concise ES6 solution featuring an optional parameter on
.
if (typeof Array.prototype.transfer === "undefined") {
Array.prototype.transfer = function(start, end, on = 1) {
this.splice(end, 0, ...this.splice(start, on))
}
}
Inspired by the initial concept put forth by wizkiddo
The variable on
represents the quantity of elements to relocate from position start
.
Additionally, here is a streamlined version that supports chaining:
if (typeof Array.prototype.transfer === "undefined") {
Array.prototype.transfer = function(start, end, on = 1) {
return this.splice(end, 0, ...this.splice(start, on)), this
}
}
[7, 8, 9, 10, 11].transfer(3, 0, 2) // => [10, 11, 7, 8, 9]
To prevent polluting prototypes, consider using a standalone utility function instead:
function transferArray(arr, start, end, on = 1) {
return arr.splice(end, 0, ...arr.splice(start, on)), arr
}
transferArray([7, 8, 9, 10, 11], 3, 0, 2) // => [10, 11, 7, 8, 9]
For non-destructive operations, a pure function can be applied without modifying the original array:
function transferredArray(arr, start, end, on = 1) {
return arr = arr.slice(), arr.splice(end, 0, ...arr.splice(start, on)), arr
}
This comprehensive approach encompasses various scenarios seen across different solutions.