Created
June 24, 2018 19:49
-
-
Save benjamingr/83a53a05635c1a5669c14a66b2d21177 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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