Skip to content

Commit

Permalink
feat: add difference and symmetricDifference to List
Browse files Browse the repository at this point in the history
  • Loading branch information
brekk committed Apr 27, 2024
1 parent 7b9f98c commit 02ca01e
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
24 changes: 21 additions & 3 deletions prelude/__internal__/List.mad
Original file line number Diff line number Diff line change
Expand Up @@ -790,9 +790,6 @@ export includes = (x, list) => where(list) {
[a, ...xs] =>
a == x || includes(x, xs)
}
// a == x ? true : includes(x, xs)



/**
* Drops n items from the given list.
Expand Down Expand Up @@ -1087,3 +1084,24 @@ export cut = (a, xs) => {
Nothing
}
}
/**
* Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list.
* @example
* difference([1,2,3,4], [7,6,5,4,3]) // [1,2]
* difference([7,6,5,4,3], [1,2,3,4]) // [7,6,5]
*/
difference :: Eq a => List a -> List a -> List a
export difference = (z, a) => reduce((stack, c) => includes(c, a) ? stack : [...stack, c], [], z)

/**
* Finds the set (i.e. no duplicates) of all elements contained in the first or second list, but not both.
* @example
* symmetricDifference([1,2,3,4], [7,6,5,4,3]) // [1,2,7,6,5]
* symmetricDifference([7,6,5,4,3], [1,2,3,4]) // [7,6,5,1,2]
*/
symmetricDifference :: Eq a => List a -> List a -> List a
export symmetricDifference = (z, a) => reduce(
(stack, c) => includes(c, a) && includes(c, z) ? stack : [...stack, c],
[],
concat(z, a),
)
14 changes: 14 additions & 0 deletions prelude/__internal__/List.spec.mad
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
concat,
contains,
cut,
difference,
drop,
dropLast,
dropWhile,
Expand Down Expand Up @@ -38,6 +39,7 @@ import {
sort,
sortDesc,
startsWith,
symmetricDifference,
tail,
tails,
take,
Expand Down Expand Up @@ -291,3 +293,15 @@ test("all - false", () => assertEquals(all((x) => x > 4, [1, 2, 10]), false))
test("cut", () => assertEquals(cut(5, range(1, 11)), Just(#[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])))
test("cut - negative index", () => assertEquals(cut(-1, range(1, 11)), Nothing))
test("cut - invalid index", () => assertEquals(cut(16, range(1, 11)), Nothing))

test("difference", () => assertEquals(difference([1, 2, 3, 4], [7, 6, 5, 4, 3]), [1, 2]))
test("difference - swap", () => assertEquals(difference([7, 6, 5, 4, 3], [1, 2, 3, 4]), [7, 6, 5]))

test(
"symmetricDifference",
() => assertEquals(symmetricDifference([1, 2, 3, 4], [7, 6, 5, 4, 3]), [1, 2, 7, 6, 5]),
)
test(
"symmetricDifference",
() => assertEquals(symmetricDifference([7, 6, 5, 4, 3], [1, 2, 3, 4]), [7, 6, 5, 1, 2]),
)

0 comments on commit 02ca01e

Please sign in to comment.