asd-xiv / m

Point free style, functional library for Javascript with focus on object arrays.
https://asd-xiv.github.io/m/
MIT License
4 stars 1 forks source link

feat: Rework `intersect`, add `overlap` #8

Closed andreidmt closed 3 years ago

andreidmt commented 3 years ago

Thoughts and proposals on #7 by @dgilperez:

Primary

  1. Rework intersect to return common and distinct items from two arrays.
  2. Add intersectBy. Allow custom predicate and merge functions, geared towards object arrays.
intersect([1, 2, 3, 3, 4], [3, 3, 4, 5])
// => [3, 4]

intersectBy(
  (a, b) => a.id === b.id,
  (a, b) => ({ ...a, ...b }),
  [
    { id: 1, lorem: "ipsum" },
    { id: 2, foo: "bar" },
  ],
  [
    { id: 2, comments: [] },
    { id: 3, comments: [] },
  ]
)
// => [{ id: 2, foo: "bar", comments: [] }]
  1. Add overlap and overlapBy functions to combine two arrays into one with distinct items.
overlap([1, 1, 2, 3, 3], [3, 3, 4, 4, 5])
// => [1, 2, 3, 4, 5]

overlapBy(
  (a, b) => a.id === b.id,
  (a, b) => ({ ...a, ...b }),
  [{ id: 1}, { id: 2 }, { id: 2 }],
  [{ id: 1, foo: "bar" }, { id: 3 }]
)
// => [{ id: 1, foo: "bar" }, { id: 2 }, { id: 3 }]

Secondary

  1. Update distinct to use shallow compare.
  2. Add distinctBy. Allow custom compare function, geared towards object arrays.
// old
distinct([1, {a: 2}, {a: 2}])
// => [1, {a: 2}]

// new
import deepEquals from "fast-deep-equal"

distinctBy(deepEquals, [1, { a: 2 }, { a: 2 }])
// => [1, {a: 2}]

Checklist

andreidmt commented 3 years ago

Hey @dgilperez, added this PR based on your #7 proposal.

Waiting for your thought and can continue with difference after we finish with these.

dgilperez commented 3 years ago

Hey, sorry for the delay @andreidmt

The changes on intersect and distinct make a lot of sense in my opinion.

Otoh, I think overlap is a confusing term - for me, overlap is almost a synonym for intersection. I'd argue the proposed implementation for overlap is actually a join. If we go to SQL joins, there are a number of different joins of course (left, right, inner, outer ...), adding to the confusion, but in general terms I think is a better term for this operation.

andreidmt commented 3 years ago

I like the idea of syncing the naming with SQL operations (where applicable). Renamed "overlap" -> "join" and the old join to "unite".

andreidmt commented 3 years ago

:tada: This PR is included in version 6.0.0 :tada:

The release is available on:

Your semantic-release bot :package::rocket: