@tidyjs/tidy
Version:
Tidy up your data with JavaScript, inspired by dplyr and the tidyverse
42 lines (39 loc) • 1.07 kB
JavaScript
import { singleOrArray } from './helpers/singleOrArray.js';
function distinct(keys) {
const _distinct = (items) => {
keys = singleOrArray(keys);
if (!keys.length) {
const set = new Set();
for (const item of items) {
set.add(item);
}
return Array.from(set);
}
const rootMap = new Map();
const distinctItems = [];
const lastKey = keys[keys.length - 1];
for (const item of items) {
let map = rootMap;
let hasItem = false;
for (const key of keys) {
const mapItemKey = typeof key === "function" ? key(item) : item[key];
if (key === lastKey) {
hasItem = map.has(mapItemKey);
if (!hasItem) {
distinctItems.push(item);
map.set(mapItemKey, true);
}
break;
}
if (!map.has(mapItemKey)) {
map.set(mapItemKey, new Map());
}
map = map.get(mapItemKey);
}
}
return distinctItems;
};
return _distinct;
}
export { distinct };
//# sourceMappingURL=distinct.js.map