locutus
Version:
Locutus other languages' standard libraries to JavaScript for fun and educational purposes
27 lines (26 loc) • 1.02 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.nubBy = nubBy;
function nubBy(items, eq) {
// discuss at: https://locutus.io/haskell/list/nubBy/
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Keeps the first occurrence of each element using a custom equality predicate, like Haskell Data.List.nubBy.
// example 1: nubBy([1, 2, 2, 3, 1], (a, b) => a === b)
// returns 1: [1, 2, 3]
// example 2: nubBy(['aa', 'ab', 'ba'], (a, b) => a.charAt(0) === b.charAt(0))
// returns 2: ['aa', 'ba']
// example 3: nubBy([], (a, b) => a === b)
// returns 3: []
if (!Array.isArray(items)) {
return [];
}
const equals = typeof eq === 'function' ? eq : (left, right) => Object.is(left, right);
const out = [];
for (const item of items) {
const duplicate = out.some((existing) => equals(item, existing));
if (!duplicate) {
out.push(item);
}
}
return out;
}