<div id='1'></div>
var arr = [1,2,3,4];
function arrayMove(arr, oldIndex, newIndex) {
const copiedArr = [arr];
const length = copiedArr.length;
if (oldIndex !== newIndex && length > oldIndex && length > newIndex) {
copiedArr.splice(newIndex, 0, copiedArr.splice(oldIndex, 1)[0]);
}
return copiedArr;
}
arrayMove(arr, 0, 3)
function arrayMove(arr, oldIndex, newIndex) {
const length = arr.length;
const itemToMove = arr[oldIndex]
if (oldIndex === newIndex || oldIndex > length || newIndex > length) {
return arr;
}
return arr.flatMap((item, index) => {
if (index === oldIndex) return [];
if (index === newIndex) return oldIndex < newIndex ? [item, itemToMove] : [itemToMove, item];
return item;
})
}
arrayMove(arr, 0, 3)
function arrayMove(arr, oldIndex, newIndex) {
const length = arr.length;
const itemToMove = arr[oldIndex]
if (oldIndex === newIndex || oldIndex > length || newIndex > length) {
return arr;
}
return arr.reduce((acc, item, index) => {
if (index === oldIndex) return acc;
if (index === newIndex) return oldIndex < newIndex ? [acc, item, itemToMove] : [acc, itemToMove, item];
return [acc, item];
}, [])
}
arrayMove(arr, 0, 3)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
splice | |
flatMap | |
reduce |
Test name | Executions per second |
---|---|
splice | 5010550.5 Ops/sec |
flatMap | 952172.3 Ops/sec |
reduce | 4747937.0 Ops/sec |
Let's break down the benchmark and analyze what's being tested.
Benchmark Definition
The benchmark defines three test cases: splice
, flatMap
, and reduce
. Each test case has a similar structure:
Options Compared
The benchmark compares three different approaches for moving an element in an array:
arr.splice(newIndex, 0, arr[oldIndex])
to insert the element at the new index.arr.flatMap((item, index) => {...})
to create a new array with the element moved.arr.reduce((acc, item, index) => {...})
to accumulate the elements of the original array and insert the moved element at the correct position.Pros and Cons
Here's a brief summary of each approach:
splice
for small to medium-sized arrays.Library
There is no explicit library mentioned in the benchmark definition. However, flatMap
is a method of the Array.prototype
object in JavaScript, so it doesn't require any external libraries.
Special JS Feature or Syntax
None of the test cases use any special JavaScript features or syntax beyond standard ECMAScript 2022.