diff options
author | Louis Pilfold <louis@lpil.uk> | 2023-10-02 22:23:51 +0100 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2023-10-02 22:23:51 +0100 |
commit | 081a4d9c417a971e00d7f0ea6706206d770d4733 (patch) | |
tree | bb602ac2f2b4cc2c341a5b7a57fbc5748137262c | |
parent | eda52ed9eee0b51efc4e3b70cdd77c60fd80447a (diff) | |
download | gleam_stdlib-081a4d9c417a971e00d7f0ea6706206d770d4733.tar.gz gleam_stdlib-081a4d9c417a971e00d7f0ea6706206d770d4733.zip |
list.key_filter
-rw-r--r-- | src/gleam/list.gleam | 34 | ||||
-rw-r--r-- | test/gleam/list_test.gleam | 20 |
2 files changed, 54 insertions, 0 deletions
diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam index 6be2f61..52e98ff 100644 --- a/src/gleam/list.gleam +++ b/src/gleam/list.gleam @@ -1448,6 +1448,40 @@ pub fn key_find( ) } +/// Given a list of 2-element tuples, finds all tuples that have a given +/// key as the first element and returns the second element. +/// +/// This function may be useful for interacting with Erlang code where lists of +/// tuples are common. +/// +/// ## Examples +/// +/// ```gleam +/// > key_filter([#("a", 0), #("b", 1), #("a", 2)], "a") +/// [0, 2] +/// ``` +/// +/// ```gleam +/// > key_filter([#("a", 0), #("b", 1)], "c") +/// [] +/// ``` +/// +pub fn key_filter( + in keyword_list: List(#(k, v)), + find desired_key: k, +) -> List(v) { + filter_map( + keyword_list, + fn(keyword) { + let #(key, value) = keyword + case key == desired_key { + True -> Ok(value) + False -> Error(Nil) + } + }, + ) +} + fn do_pop(haystack, predicate, checked) { case haystack { [] -> Error(Nil) diff --git a/test/gleam/list_test.gleam b/test/gleam/list_test.gleam index 321f5a4..ae066ad 100644 --- a/test/gleam/list_test.gleam +++ b/test/gleam/list_test.gleam @@ -821,6 +821,26 @@ pub fn key_find_test() { |> should.equal(Error(Nil)) } +pub fn key_filter_test() { + let proplist = [#(0, "1"), #(1, "2"), #(0, "3"), #(1, "4"), #(2, "5")] + + proplist + |> list.key_filter(0) + |> should.equal(["1", "3"]) + + proplist + |> list.key_filter(1) + |> should.equal(["2", "4"]) + + proplist + |> list.key_filter(2) + |> should.equal(["5"]) + + proplist + |> list.key_filter(3) + |> should.equal([]) +} + pub fn pop_test() { [1, 2, 3] |> list.pop(fn(x) { x > 2 }) |