2020-07-16 14:46:13 +00:00
|
|
|
// Copyright 2020 the V8 project authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
|
|
// found in the LICENSE file.
|
|
|
|
|
2020-11-18 15:51:07 +00:00
|
|
|
export function delay(time) {
|
2020-10-29 20:42:07 +00:00
|
|
|
return new Promise(resolver => setTimeout(resolver, time));
|
2020-11-30 18:38:13 +00:00
|
|
|
}
|
2020-12-07 08:44:54 +00:00
|
|
|
|
2021-06-22 13:32:53 +00:00
|
|
|
export function defer() {
|
|
|
|
let resolve_func, reject_func;
|
|
|
|
const p = new Promise((resolve, reject) => {
|
|
|
|
resolve_func = resolve;
|
|
|
|
reject_func = resolve;
|
|
|
|
});
|
|
|
|
p.resolve = resolve_func;
|
|
|
|
p.reject = reject_func;
|
|
|
|
return p;
|
|
|
|
}
|
|
|
|
|
2020-12-07 08:44:54 +00:00
|
|
|
export class Group {
|
|
|
|
constructor(key, id, parentTotal, entries) {
|
|
|
|
this.key = key;
|
|
|
|
this.id = id;
|
|
|
|
this.entries = entries;
|
2021-07-05 08:01:09 +00:00
|
|
|
this.length = entries.length;
|
2020-12-07 08:44:54 +00:00
|
|
|
this.parentTotal = parentTotal;
|
|
|
|
}
|
|
|
|
|
|
|
|
get percent() {
|
2021-07-05 08:01:09 +00:00
|
|
|
return this.length / this.parentTotal * 100;
|
2020-12-07 08:44:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
add() {
|
2021-07-05 08:01:09 +00:00
|
|
|
this.length++;
|
2020-12-07 08:44:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
addEntry(entry) {
|
2021-07-05 08:01:09 +00:00
|
|
|
this.length++;
|
2020-12-07 08:44:54 +00:00
|
|
|
this.entries.push(entry);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export function groupBy(array, keyFunction, collect = false) {
|
|
|
|
if (array.length === 0) return [];
|
|
|
|
if (keyFunction === undefined) keyFunction = each => each;
|
|
|
|
const keyToGroup = new Map();
|
|
|
|
const groups = [];
|
2021-07-05 08:01:09 +00:00
|
|
|
const sharedEmptyArray = [];
|
2020-12-07 08:44:54 +00:00
|
|
|
let id = 0;
|
|
|
|
// This is performance critical, resorting to for-loop
|
|
|
|
for (let each of array) {
|
|
|
|
const key = keyFunction(each);
|
|
|
|
let group = keyToGroup.get(key);
|
|
|
|
if (group !== undefined) {
|
|
|
|
collect ? group.addEntry(each) : group.add();
|
|
|
|
continue;
|
|
|
|
}
|
2021-07-05 08:01:09 +00:00
|
|
|
let entries = collect ? [each] : sharedEmptyArray;
|
2020-12-07 08:44:54 +00:00
|
|
|
group = new Group(key, id++, array.length, entries);
|
|
|
|
groups.push(group);
|
|
|
|
keyToGroup.set(key, group);
|
|
|
|
}
|
2021-11-18 09:53:32 +00:00
|
|
|
// Sort by length
|
|
|
|
return groups.sort((a, b) => b.length - a.length);
|
|
|
|
}
|
2021-12-17 03:09:34 +00:00
|
|
|
|
|
|
|
export * from '../js/helper.mjs'
|