perf(intersectionBy): Optimize time complexity (#44)

This commit is contained in:
Changwan 2024-06-13 20:27:37 +09:00 committed by GitHub
parent d22d241ea6
commit 0a02cdcaea
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -19,9 +19,6 @@
* // result will be [{ id: 2 }] since only this element has a matching id in both arrays.
*/
export function intersectionBy<T, U>(firstArr: T[], secondArr: T[], mapper: (item: T) => U): T[] {
const mappedSecondArr = secondArr.map(x => mapper(x));
return firstArr.filter(item => {
return mappedSecondArr.includes(mapper(item));
});
const mappedSecondSet = new Set(secondArr.map(mapper));
return firstArr.filter(item => mappedSecondSet.has(mapper(item)));
}