Skip to content

Instantly share code, notes, and snippets.

@KelvinCoding
Created December 10, 2019 05:45
Show Gist options
  • Save KelvinCoding/0c3954a603e7ce52e2162afc7ed4edb2 to your computer and use it in GitHub Desktop.
Save KelvinCoding/0c3954a603e7ce52e2162afc7ed4edb2 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>merge-testing</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/1.0.0/benchmark.min.js"></script>
<script src="./suite.js"></script>
</head>
<body>
<h1>Open the console to view the results</h1>
<h2><code>cmd + alt + j</code> or <code>ctrl + alt + j</code></h2>
</body>
</html>
"use strict";
(function (factory) {
if (typeof Benchmark !== "undefined") {
factory(Benchmark);
} else {
factory(require("benchmark"));
}
})(function (Benchmark) {
var suite = new Benchmark.Suite;
Benchmark.prototype.setup = function () {
const arr_len = 10;
const arr_types = 3;
const alphabet = 'abcdefghijklmnopqrstuvwxyz';
const all_arrays = [];
const arr_names = [...Array(arr_types).keys()].map((id) => {
const arr_num = Math.floor(id / alphabed.length);
const arr_key = alphabet.charAt(id % alphabet.length);
const arr_name = `${arr_key}_${arr_num}`;
return arr_name;
});
const all_named_arrays = arr_names.reduce((agg, name) => {
agg[`${name}`] = [...Array(arr_len).keys()].map((id) => {
const item = {
foo_id: id,
};
item[`text_${name}`] = `${name}_${id}`;
return item;
});
}, {});
const ids = [...Array(arr_len).keys()];
};
suite.add("via function", function () {
// via function
function merge_foo_items(id, ...named_items) {
const result = {
foo_id: id,
};
named_items.keys().forEach((key) => {
result[key] = named_items[key].find((item) => item.foo_id === id)[`text_${key}`];
});
return result;
}
ids.map((id) => merge_foo_items(id, ...all_named_arrays))
});
suite.add("loop each", function () {
// loop each
const result = ids.reduce((agg,id) => {
agg[id] = {
foo_id: id,
};
return agg;
}, {});
all_named_arrays.keys().forEach((key) => {
all_named_arrays[key].forEach((item) => {
result[item.foo_id][`text_${key}`] = item[`text_${key}`];
});
});
});
suite.on("cycle", function (evt) {
console.log(" - " + evt.target);
});
suite.on("complete", function (evt) {
console.log(new Array(30).join("-"));
var results = evt.currentTarget.sort(function (a, b) {
return b.hz - a.hz;
});
results.forEach(function (item) {
console.log((idx + 1) + ". " + item);
});
});
console.log("merge-testing");
console.log(new Array(30).join("-"));
suite.run();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment