Skip to content

Instantly share code, notes, and snippets.

@darcien
Created November 21, 2018 15:56
Show Gist options
  • Save darcien/8e4a73bfaf9ea0ef533ece380e645780 to your computer and use it in GitHub Desktop.
Save darcien/8e4a73bfaf9ea0ef533ece380e645780 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>getUniqueList</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 () {
let data = [
{
name: 'A',
age: 7,
},
{
name: 'B',
age: 12,
},
{
name: 'C',
age: 17,
},
{
name: 'A',
age: 23,
},
];
};
suite.add("let getList = (data, key) => {", function () {
let getList = (data, key) => {
return [...new Set(data.reduce((acc, item) => {
if (item.hasOwnProperty(key)) {
return acc.concat(item[key])
}
return acc;
}, []))]
}
getList(data, 'name');
});
suite.add("let getListMK2 = (data, key) => {", function () {
let getListMK2 = (data, key) => {
let list = new Set(data.map(item => item[key]));
list.delete(null);
list.delete(undefined);
return [...list]
}
getListMK2(data, 'name');
});
suite.add("function getUniqueList(", function () {
function getUniqueList(
list,
key,
) {
return [...new Set(list.map((data) => data[key]))].filter(
(datum) => datum != null,
);
}
getUniqueList(data, 'name')
});
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("getUniqueList");
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