Skip to content

Instantly share code, notes, and snippets.

@mhkeller
Last active December 3, 2021 04:19
Show Gist options
  • Save mhkeller/c7509fdc7dc4e177cfbb9419b6cde92e to your computer and use it in GitHub Desktop.
Save mhkeller/c7509fdc7dc4e177cfbb9419b6cde92e to your computer and use it in GitHub Desktop.
d3-array's group and groups functions
class InternMap extends Map {
constructor(entries, key = keyof) {
super();
Object.defineProperties(this, {_intern: {value: new Map()}, _key: {value: key}});
if (entries != null) for (const [key, value] of entries) this.set(key, value);
}
get(key) {
return super.get(intern_get(this, key));
}
has(key) {
return super.has(intern_get(this, key));
}
set(key, value) {
return super.set(intern_set(this, key), value);
}
delete(key) {
return super.delete(intern_delete(this, key));
}
}
function intern_get({_intern, _key}, value) {
const key = _key(value);
return _intern.has(key) ? _intern.get(key) : value;
}
function intern_set({_intern, _key}, value) {
const key = _key(value);
if (_intern.has(key)) return _intern.get(key);
_intern.set(key, value);
return value;
}
function intern_delete({_intern, _key}, value) {
const key = _key(value);
if (_intern.has(key)) {
value = _intern.get(key);
_intern.delete(key);
}
return value;
}
function keyof(value) {
return value !== null && typeof value === "object" ? value.valueOf() : value;
}
function nest(values, map, reduce, keys) {
return (function regroup(values, i) {
if (i >= keys.length) return reduce(values);
const groups = new InternMap();
const keyof = keys[i++];
let index = -1;
for (const value of values) {
const key = keyof(value, ++index, values);
const group = groups.get(key);
if (group) group.push(value);
else groups.set(key, [value]);
}
for (const [key, values] of groups) {
groups.set(key, regroup(values, i));
}
return map(groups);
})(values, 0);
}
function identity(d) {
return d;
}
function group(values, ...keys) {
return nest(values, identity, identity, keys);
}
function groups(values, ...keys) {
return nest(values, Array.from, identity, keys);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment