Last active
June 29, 2020 07:57
-
-
Save kotarovivino/6e417edbb91fe8c78b34bce830ad8449 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
const list1 = [1,2,3] | |
const list2 = [3,6,8,2] | |
const list3 = [] | |
const list4 = [3] | |
expect(intersect(list1,list2).toBe([2,3]) | |
expect(intersect(list1,list3).toBe([]) | |
expect(intersect(list2,list4).toBe([3]) | |
// we shouldn't give this upfront, | |
// and let candidates figure out what test cases should be added | |
const list5 = [2,2,3,4]; | |
expect(intersect(list1,list5).toBe([2,3]); | |
function intersect(list1, list2) { | |
// turn list2 into a hash map | |
const object2 = list2.reduce((memo, item) => { | |
memo[item] = true; | |
return memo; | |
}, {}); | |
const alreadyAdded = {}; | |
// iterate only once over list1 | |
return list1.filter((item) => { | |
if (!alreadyAdded[item] && object2[item]) { | |
alreadyAdded[item] = true; | |
return true | |
} | |
return false; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment