const createLists = (arr = []) => Array.from(
arr.reduce((map, val) => {
if (!map.has(val)) map.set(val, []);
map.get(val).push(val);
return map;
}, new Map()).values()
);
console.log(createLists([1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0]));
function createLists(arr = []) {
let authors = [];
let list = [];
arr.forEach(item => {
let authorIndex = authors.includes(item) ? authors.indexOf(item) : (authors.push(item) - 1);
list[authorIndex] = list[authorIndex] || [];
list[authorIndex].push(item);
});
return list;
}
console.log(createLists([1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0]));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Map | |
forEach |
Test name | Executions per second |
---|---|
Map | 23956.1 Ops/sec |
forEach | 20761.6 Ops/sec |
Let's break down the benchmark and its test cases.
Benchmark Overview
The benchmark compares two approaches to create an array of values with nested structure:
Map
data structure to store values and their indices, then converts it to an array using Array.from()
.forEach()
and creates an array by pushing values into a dynamically-sized array.Options Compared
The two options being compared are:
Map
data structure to store values with their indices, allowing for efficient lookup and iteration.forEach()
to iterate over the input array, creating an array by pushing values into a dynamically-sized array.Pros and Cons
Map:
Pros:
Map
stores only unique keys (values) with their indices.Cons:
Map
object.forEach:
Pros:
Map
in this case).Cons:
Other Considerations
Both approaches have trade-offs between memory usage, iteration efficiency, and input order requirements. The choice of approach depends on the specific use case and requirements.
In this benchmark, the Map
approach tends to outperform forEach
, likely due to its efficient use of memory and fast iteration capabilities.
Now, let's talk about some JavaScript-specific features mentioned in the benchmark:
=>
): Used for concise function definitions, similar to traditional functions but with fewer keywords.Note: The forEach()
function is not a special JS feature per se, but rather a part of the standard JavaScript API.