1# Copyright 2017 The Bazel Authors. All rights reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15"""Skylib module containing functions that operate on collections.""" 16 17def _after_each(separator, iterable): 18 """Inserts `separator` after each item in `iterable`. 19 20 Args: 21 separator: The value to insert after each item in `iterable`. 22 iterable: The list into which to intersperse the separator. 23 24 Returns: 25 A new list with `separator` after each item in `iterable`. 26 """ 27 result = [] 28 for x in iterable: 29 result.append(x) 30 result.append(separator) 31 32 return result 33 34def _before_each(separator, iterable): 35 """Inserts `separator` before each item in `iterable`. 36 37 Args: 38 separator: The value to insert before each item in `iterable`. 39 iterable: The list into which to intersperse the separator. 40 41 Returns: 42 A new list with `separator` before each item in `iterable`. 43 """ 44 result = [] 45 for x in iterable: 46 result.append(separator) 47 result.append(x) 48 49 return result 50 51def _uniq(iterable): 52 """Returns a list of unique elements in `iterable`. 53 54 Requires all the elements to be hashable. 55 56 Args: 57 iterable: An iterable to filter. 58 59 Returns: 60 A new list with all unique elements from `iterable`. 61 """ 62 unique_elements = {element: None for element in iterable} 63 64 # list() used here for python3 compatibility. 65 # TODO(bazel-team): Remove when testing frameworks no longer require python compatibility. 66 return list(unique_elements.keys()) 67 68collections = struct( 69 after_each = _after_each, 70 before_each = _before_each, 71 uniq = _uniq, 72) 73