Skip to content

Commit

Permalink
Add inner_product filter
Browse files Browse the repository at this point in the history
  • Loading branch information
teddyphreak committed Oct 24, 2024
1 parent cced2a1 commit 57e35ae
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 1 deletion.
2 changes: 1 addition & 1 deletion galaxy.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
namespace: nephelaiio
name: plugins
version: 0.0.7
version: 0.0.8
readme: README.md
authors:
- Ted Cook <[email protected]>
Expand Down
10 changes: 10 additions & 0 deletions molecule/default/verify.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,13 @@
expected: [["a"]]
filter: "nephelaiio.plugins.set_difference"
result: "{{ pairs | map(filter) }}"

- name: Test inner_product
ansible.builtin.assert:
that: result == expected
fail_msg: "{{ result | to_json }}"
vars:
pairs: [[["a", "b"], ["@c", "@d"]]]
expected: [["a@c", "a@d", "b@c", "b@d"]]
filter: "nephelaiio.plugins.inner_product"
result: "{{ pairs | map(filter) | map('map', 'join') }}"
12 changes: 12 additions & 0 deletions plugins/filter/custom_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -732,6 +732,17 @@ def set_difference(value):
return list(set(a).difference(set(b)))


def inner_product(value):
"""
Return the inner product of an array pair:
.. sourcecode:: jinja
{{ [['a', 'b', ['c', 'd']] | map("inner_product") }}
-> [['a, 'c'], ['a', 'd'], ['b', 'c'], ['b', 'd']]
"""
[a, b] = value
return [list(x) for x in itertools.product(a, b)]


class FilterModule:
"""
A class encapsulating a collection of jinja2 filters.
Expand Down Expand Up @@ -819,4 +830,5 @@ def filters(self):
"is_all_true": is_all_true,
"search_regex": search_regex,
"set_difference": set_difference,
"inner_product": inner_product,
}
20 changes: 20 additions & 0 deletions tests/test_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
alias_keys,
drop_attributes,
filename,
inner_product,
ip_range,
is_all_true,
is_any_true,
Expand Down Expand Up @@ -478,3 +479,22 @@ def test_set_difference():
assert set(set_difference([["a", "b"], ["a", "d"]])).difference(set(["b"])) == set()
assert set(set_difference([["a", "b"], ["b", "c"]])).difference(set(["a"])) == set()
assert set(set_difference([["a", "b"], ["a", "b"]])).difference(set([])) == set()


def test_inner_product():
assert inner_product([[], []]) == []
assert inner_product([["a"], ["b"]]) == [["a", "b"]]
assert inner_product([["a", "b"], ["c"]]) == [
["a", "c"],
["b", "c"],
]
assert inner_product([["a"], ["c", "d"]]) == [
["a", "c"],
["a", "d"],
]
assert inner_product([["a", "b"], ["c", "d"]]) == [
["a", "c"],
["a", "d"],
["b", "c"],
["b", "d"],
]

0 comments on commit 57e35ae

Please sign in to comment.