Skip to content

Commit

Permalink
feat: Add "intersect" for joining two arrays using predicate and unio…
Browse files Browse the repository at this point in the history
…n functions
  • Loading branch information
andreidmt committed Apr 7, 2020
1 parent b5bc839 commit 45f6750
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export { hist } from "./hist/hist"
export { i } from "./i/i"
export { inc } from "./inc/inc"
export { indexBy } from "./index-by/index-by"
export { intersect } from "./intersect/intersect"
export { is, isNothing, isTrue, isFalse, isObject } from "./is/is"
export { isEmpty, isNotEmpty } from "./is-empty/is-empty"
export { isMatch } from "./is-match/is-match"
Expand Down
26 changes: 26 additions & 0 deletions src/intersect/intersect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { findIndex } from "../find-index/find-index"

export const intersect = (predicateFn, unionFn) => (aList, bList) => {
if (aList.length === 0) {
return bList
}

if (bList.length === 0) {
return aList
}

const result = [].concat(aList)

for (let index = 0; index < bList.length; ++index) {
const b = bList[index]
const aIndex = findIndex(item => predicateFn(item, b))(result)

if (aIndex === -1) {
result.push(b)
} else {
result[aIndex] = unionFn(result[aIndex], b)
}
}

return result
}
55 changes: 55 additions & 0 deletions src/intersect/intersect.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import test from "tape"

import { intersect } from ".."

test("array::intersect", t => {
t.deepEqual(
intersect(
(a, b) => a === b,
a => a
)([], [1, 2, 3]),
[1, 2, 3],
"First array empty"
)

t.deepEqual(
intersect(
(a, b) => a === b,
a => a
)([1, 2, 3], []),
[1, 2, 3],
"Second array empty"
)

t.deepEqual(
intersect(
(a, b) => a === b,
a => a
)([1, 2, 3], [3, 4, 5]),
[1, 2, 3, 4, 5],
"Join with common"
)

t.deepEqual(
intersect(
(a, b) => a === b,
a => a
)([1, 2], [3, 4, 5]),
[1, 2, 3, 4, 5],
"Join without common"
)

t.deepEqual(
intersect(
(a, b) => a.id === b.id,
(a, b) => ({ ...a, ...b })
)(
[{ id: 1, overwrite: 1 }, { id: 2 }],
[{ id: 1, overwrite: 2 }, { id: 3 }]
),
[{ id: 1, overwrite: 2 }, { id: 2 }, { id: 3 }],
"Join objects - same order as input arrays"
)

t.end()
})

0 comments on commit 45f6750

Please sign in to comment.