aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLouis Pilfold <louis@lpil.uk>2020-07-14 21:21:44 +0100
committerLouis Pilfold <louis@lpil.uk>2020-07-14 21:21:44 +0100
commit48d458d4f5785607fa236fd70e8dd773ab014699 (patch)
tree9c0e4fcd0b454fa010b81c668cb3db240b36160c
parent0cff914b427e2d37a3b889e0f9586ab59cef3d39 (diff)
downloadgleam_stdlib-48d458d4f5785607fa236fd70e8dd773ab014699.tar.gz
gleam_stdlib-48d458d4f5785607fa236fd70e8dd773ab014699.zip
list.key_set
-rw-r--r--CHANGELOG.md1
-rw-r--r--src/gleam/list.gleam27
-rw-r--r--test/gleam/list_test.gleam10
3 files changed, 37 insertions, 1 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f706231..508db58 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@
`of`.
- The `dynamic` module gains the `any` function.
- The `bit_builder` module gains the `from_string` function.
+- The `list` module gains the `key_set` function.
## v0.10.1 - 2020-07-01
diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam
index b13575b..06e5a33 100644
--- a/src/gleam/list.gleam
+++ b/src/gleam/list.gleam
@@ -954,7 +954,10 @@ pub fn pop_map(
/// > key_pop([tuple("a", 0), tuple("b", 1)], "c")
/// Error(Nil)
///
-pub fn key_pop(haystack, key) {
+pub fn key_pop(
+ haystack: List(tuple(k, v)),
+ key: k,
+) -> Result(tuple(v, List(tuple(k, v))), Nil) {
pop_map(
haystack,
fn(entry) {
@@ -966,3 +969,25 @@ pub fn key_pop(haystack, key) {
},
)
}
+
+/// Given a list of 2 element tuples, insert a key and value into the list.
+///
+/// If there was already a tuple with the key then it is replaced, otherwise it
+/// is added to the end of the list.
+///
+///
+/// ## Examples
+///
+/// > key_set([tuple(5, 0), tuple(4, 1)], 4, 100)
+/// [tuple(5, 0), tuple(4, 100)]
+///
+/// > key_set([tuple(5, 0), tuple(4, 1)], 1, 100)
+/// [tuple(5, 0), tuple(4, 1), tuple(1, 100)]
+///
+pub fn key_set(list: List(tuple(a, b)), key: a, value: b) -> List(tuple(a, b)) {
+ case list {
+ [] -> [tuple(key, value)]
+ [tuple(k, _), ..rest] if k == key -> [tuple(key, value), ..rest]
+ [first, ..rest] -> [first, ..key_set(rest, key, value)]
+ }
+}
diff --git a/test/gleam/list_test.gleam b/test/gleam/list_test.gleam
index ef096f6..31f8f27 100644
--- a/test/gleam/list_test.gleam
+++ b/test/gleam/list_test.gleam
@@ -457,3 +457,13 @@ pub fn key_pop_test() {
list.key_pop([tuple("a", 0), tuple("b", 1)], "c")
|> should.equal(Error(Nil))
}
+
+pub fn key_set_test() {
+ [tuple(5, 0), tuple(4, 1)]
+ |> list.key_set(4, 100)
+ |> should.equal([tuple(5, 0), tuple(4, 100)])
+
+ [tuple(5, 0), tuple(4, 1)]
+ |> list.key_set(1, 100)
+ |> should.equal([tuple(5, 0), tuple(4, 1), tuple(1, 100)])
+}