Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions coding-intermediate/intersection.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,18 @@ function intersection(left, right) {
// if we didn't use this object, we'd have to check
// if result contains current on every turn of the
// loop, which would take up to O(N * log(N)) time.
let seen = left.reduce((seen, item) => {
seen[item] = true
return seen
}, {})
//
// "new Set()" doesn't allow duplicates
const seen = new Set(left)

return right.reduce((result, current) => {
if (current in seen) {
return result.concat(current)
const result = right.reduce((result, num) => {
if (seen.has(num)) {
return result.add(num)
}
seen[current] = true
return result
}, [])
}, new Set())

return Array.from(result)
}

/// tests
Expand All @@ -29,3 +29,4 @@ import { test } from 'ava'

test(t => t.deepEqual(intersection([1, 5, 4, 2], [8, 91, 4, 1, 3]), [4, 1]))
test(t => t.deepEqual(intersection([1, 5, 4, 2], [7, 12]), []))
test(t => t.deepEqual(intersection([1, 5, 1, 10], [5, 1, 5, 12]), [5, 1]))