Matias
October 5, 2021, 9:11pm
1
Hi Friends, i commonly used function like this
function moveIndexOfArray(arr, indexFrom, indexTo)
{
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
}
It would be convenient for the method to do it natively and thus avoid this, what do you think?
ex: myArray.moveIndexTo(... or something like this
You can solve the performance problem using copyWithin
:
function moveIndexOfArray(arr, indexFrom, indexTo) {
let temp = arr[indexFrom]
let source = indexFrom, dest = indexTo
if (source < dest) { source = indexTo; dest = indexFrom }
arr.copyWithin(source, source + 1, dest)
arr[indexTo] = temp
}
(This is of course untested and might not be 100% correct, but you get the gist.)
Edit: it's also worth noting that not even C++ has a "move item" or "move index" method for its vectors , nor does it have anything that does that in its <algorithms>
library .
Actually C++ has std::rotate which is a more generic way to do this, i.e. you rotate left or right (depending on indexFrom < indexTo
) by 1.
1 Like
Oh, I missed that. Also worth noting Java has it indirectly (they explain how to do it in the docs for the method), and Rust likewise supports it indirectly via slice.rotate_{left,right}(mid)
+ subslice syntax . But Python has no such method for lists nor binary sequences , nor does it have anything of use in its builtins or its itertools module - you'd necessarily have to roll it yourself.
+1 for a rotate
function, I frequently use it in my project related to music theory (I am currently using arr.concat(arr).slice(index, index + arr.length)
, which has a bad performance (though I donβt care much)).