diff --git a/docs/collections_doc.md b/docs/collections_doc.md index cd9db8b1..cc8b6dbe 100755 --- a/docs/collections_doc.md +++ b/docs/collections_doc.md @@ -73,3 +73,27 @@ Requires all the elements to be hashable. A new list with all unique elements from `iterable`. + + +## collections.flatten + +
+collections.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. + +**PARAMETERS** + + +| Name | Description | Default Value | +| :------------- | :------------- | :------------- | +| iterable | An iterable to be collapsed to a list. | none | + +**RETURNS** + +A new list with the collapsed elements from `iterable`. + + diff --git a/lib/collections.bzl b/lib/collections.bzl index f41eea2e..5f59a2df 100644 --- a/lib/collections.bzl +++ b/lib/collections.bzl @@ -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, ) diff --git a/tests/collections_tests.bzl b/tests/collections_tests.bzl index 9e866721..1c911e49 100644 --- a/tests/collections_tests.bzl +++ b/tests/collections_tests.bzl @@ -103,6 +103,23 @@ 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( @@ -110,4 +127,5 @@ def collections_test_suite(): after_each_test, before_each_test, uniq_test, + flatten_test, )