Skip to content

Instantly share code, notes, and snippets.

@yiningv
Created July 26, 2022 10:15
Show Gist options
  • Save yiningv/d859289f3ba9dbf9a8167af0ffe84595 to your computer and use it in GitHub Desktop.
Save yiningv/d859289f3ba9dbf9a8167af0ffe84595 to your computer and use it in GitHub Desktop.
JS对可迭代对象的聚合处理
function frequencies_by(enumerable, key_fn) {
key_fn = key_fn || (x => x);
const result = {};
enumerable.forEach(e => {
const key = key_fn(e);
result[key] = result[key] || 0;
result[key] += 1;
});
return result;
}
function group_by(enumerable, key_fn, value_fn) {
value_fn = value_fn || (x => x);
const groups = {};
enumerable.forEach(e => {
const group = key_fn(e);
groups[group] = groups[group] || [];
groups[group].push(value_fn(e));
});
return groups;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment