From 07f9c7af8e096c0533b741bfaa1c1fc091dea0d5 Mon Sep 17 00:00:00 2001 From: Pekka Laiho Date: Tue, 8 Dec 2020 16:02:56 +0700 Subject: [PATCH] added functions unset and unset! --- README.md | 2 ++ src/Hash.php | 11 +++++++++++ src/Lib/Collections.php | 14 ++++++++++++++ 3 files changed, 27 insertions(+) diff --git a/README.md b/README.md index df0733d..99c3cf1 100644 --- a/README.md +++ b/README.md @@ -329,6 +329,8 @@ reverse | `(reverse [1 2 3])` | `[3 2 1]` | Reverse the order of a sequence. Use key? | `(key? {"a" "b"} "a")` | `true` | Return true if the hash-map contains the given key. set | `(set {"a" 1} "b" 2)` | `{"a":1 "b":2}` | Create new hash-map which contains the given key-value pair. set! | `(set! {"a" 1} "b" 2)` | `2` | Modify the given hash-map by setting the given key-value pair and return the set value. **This function is mutable!** +unset | `(unset {"a":1 "b":2 "c":3} "b")` | `{"a":1 "c":3}` | Create a new hash-map with the given key removed. +unset! | `(unset! {"a":1 "b":2 "c":3} "b")` | `2` | Modify the given hash-map by removing the given key and return the corresponding value. **This function is mutable!** keys | `(keys {"a" 1 "b" 2})` | `("a" "b")` | Return a list of the keys for a hash-map. values | `(values {"a" 1 "b" 2})` | `(1 2)` | Return a list of the values for a hash-map. zip | `(zip ["a" "b"] [1 2])` | `{"a":1 "b":2}` | Create a hash-map using the first sequence as keys and the second as values. Uses [array_combine](https://www.php.net/manual/en/function.array-combine.php) internally. diff --git a/src/Hash.php b/src/Hash.php index 1ce8ee8..48a1365 100644 --- a/src/Hash.php +++ b/src/Hash.php @@ -17,4 +17,15 @@ class Hash extends Collection $this->data[$key] = $value; return $value; } + + public function unset(string $key) + { + if (array_key_exists($key, $this->data)) { + $value = $this->data[$key]; + unset($this->data[$key]); + return $value; + } + + return null; + } } diff --git a/src/Lib/Collections.php b/src/Lib/Collections.php index 3fc675f..d9bf3a7 100644 --- a/src/Lib/Collections.php +++ b/src/Lib/Collections.php @@ -255,6 +255,20 @@ class Collections implements ILib } )); + $env->set('unset', new CoreFunc('unset', 'Create a new hash-map from the first argument with the given key removed.', 2, 2, + function (Hash $a, string $key) { + $data = $a->getData(); + unset($data[$key]); + return new Hash($data); + } + )); + + $env->set('unset!', new CoreFunc('unset!', 'Modify the hash-map (first argument) and remove the given key.', 2, 2, + function (Hash $a, string $key) { + return $a->unset($key); + } + )); + $env->set('keys', new CoreFunc('keys', 'Return the keys of a hash-map as a list.', 1, 1, fn (Hash $a) => new MList(array_keys($a->getData())) ));