Skip to content
Open
Show file tree
Hide file tree
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
24 changes: 24 additions & 0 deletions docs/collections_doc.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,27 @@ Requires all the elements to be hashable.
A new list with all unique elements from `iterable`.


<a id="collections.flatten"></a>

## collections.flatten

<pre>
collections.flatten(<a href="#collections.flatten-iterable">iterable</a>)
</pre>

Flattens an iterable to the sum of the elements with a starting value of [].

This behaves like collapsing the first dimension of the iterable.

**PARAMETERS**


| Name | Description | Default Value |
| :------------- | :------------- | :------------- |
| <a id="collections.flatten-iterable"></a>iterable | An iterable to be collapsed to a list. | none |

**RETURNS**

A new list with the collapsed elements from `iterable`.


17 changes: 17 additions & 0 deletions lib/collections.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,25 @@ def _uniq(iterable):
# TODO(bazel-team): Remove when testing frameworks no longer require python compatibility.
return list(unique_elements.keys())

def _flatten(iterable):
"""Flattens an iterable to the sum of the elements with a starting value of [].

This behaves like collapsing the first dimension of the iterable.

Args:
iterable: An iterable to be collapsed to a list.

Returns:
A new list with the collapsed elements from `iterable`.
"""
result = []
for element in iterable:
result += element
return result

collections = struct(
after_each = _after_each,
before_each = _before_each,
uniq = _uniq,
flatten = _flatten,
)
18 changes: 18 additions & 0 deletions tests/collections_tests.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,29 @@ def _uniq_test(ctx):

uniq_test = unittest.make(_uniq_test)

def _flatten_test(ctx):
env = unittest.begin(ctx)
asserts.equals(env, [0, 1, 2, 3], collections.flatten([[0, 1], [2, 3]]))
asserts.equals(env, [], collections.flatten([]), [])
asserts.equals(env, [0, 1], collections.flatten([[], [0, 1]]))
asserts.equals(env,
'[] + select({"//conditions:default": [0, 1]}) + select({"//conditions:default": [2, 3]})',
str(collections.flatten([select({
"//conditions:default": [0, 1],
}), select({
"//conditions:default": [2, 3],
})])))

return unittest.end(env)

flatten_test = unittest.make(_flatten_test)

def collections_test_suite():
"""Creates the test targets and test suite for collections.bzl tests."""
unittest.suite(
"collections_tests",
after_each_test,
before_each_test,
uniq_test,
flatten_test,
)