Skip to content

Instantly share code, notes, and snippets.

@benjamingr
Created June 24, 2018 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benjamingr/83a53a05635c1a5669c14a66b2d21177 to your computer and use it in GitHub Desktop.
Save benjamingr/83a53a05635c1a5669c14a66b2d21177 to your computer and use it in GitHub Desktop.
// generators are lazy so maxItems isn't needed anymore - you just take as many items as you need
// it's also lazy, so if you need less items you will pay less for it. Naming a Set `set` is like naming a Number `number`
const uniqueMergeWithoutMax = function *(arrays, withoutValue) {
const seen = new Set();
for(const array of arrays) {
for(const item of array) {
if (item === withoutValue || seen.has(item)) continue;
seen.add(item);
yield item;
}
}
};
const uniqueMergeWithoutMax = (arrays, withoutValue, maxItems) => {
const set = new Set();
const res = [];
const iterator = (item) => {
if (item !== withoutValue && !set.has(item)) {
set.add(item);
res.push(item);
}
};
for (let arraysIndex = 0, arraysLength = arrays.length; arraysIndex < arraysLength; arraysIndex++) {
const currentArray = arrays[arraysIndex];
for (let index = 0, currentArrayLength = currentArray.length; index < currentArrayLength; index++) {
const item = currentArray[index];
if (res.length === maxItems) {
return res;
}
iterator(item);
}
}
return res;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment