Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(list): add unique function #716

Merged
merged 5 commits into from
Feb 27, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
26 changes: 26 additions & 0 deletions docs/lists.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion lib/lists.bzl
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"Functions for lists"

load("//lib/private:lists.bzl", _every = "every", _filter = "filter", _find = "find", _map = "map", _once = "once", _pick = "pick", _some = "some")
load("//lib/private:lists.bzl", _every = "every", _filter = "filter", _find = "find", _map = "map", _once = "once", _pick = "pick", _some = "some", _unique = "unique")

every = _every
filter = _filter
Expand All @@ -9,3 +9,4 @@ map = _map
once = _once
pick = _pick
some = _some
unique = _unique
18 changes: 18 additions & 0 deletions lib/private/lists.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -117,3 +117,21 @@ def some(f, arr):
if f(a):
return True
return False

def unique(arr):
alexeagle marked this conversation as resolved.
Show resolved Hide resolved
"""Return a new list with unique items in it.

Example:
`unique(["foo", "bar", "foo", "baz"]) // ["foo", "bar", "baz"]`

Args:
arr: List to iterate over

Returns:
A new list with unique items
"""
res = []
for a in arr:
if a not in res:
res.append(a)
return res
12 changes: 11 additions & 1 deletion lib/tests/lists_test.bzl
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""unit tests for lists"""

load("@bazel_skylib//lib:unittest.bzl", "asserts", "unittest")
load("//lib/private:lists.bzl", "every", "filter", "find", "map", "once", "pick", "some")
load("//lib/private:lists.bzl", "every", "filter", "find", "map", "once", "pick", "some", "unique")

def _every_test_impl(ctx):
env = unittest.begin(ctx)
Expand Down Expand Up @@ -70,6 +70,15 @@ def _some_test_impl(ctx):

some_test = unittest.make(_some_test_impl)

def _unique_test_impl(ctx):
env = unittest.begin(ctx)

asserts.equals(env, unique(["foo", {"bar": "baz"}, 42, {"bar": "baz"}, "foo"]), ["foo", {"bar": "baz"}, 42])

return unittest.end(env)

unique_test = unittest.make(_unique_test_impl)

def lists_test_suite():
unittest.suite(
"lists_tests",
Expand All @@ -80,4 +89,5 @@ def lists_test_suite():
once_test,
pick_test,
some_test,
unique_test,
)