From 44e78679e898e70ee18b0a7c73897384379683bb Mon Sep 17 00:00:00 2001 From: Justin Lin Date: Fri, 27 Mar 2020 13:53:07 +0800 Subject: [PATCH] add assoc --- src/experimental/_impl/_assoc_impl.scad | 14 ++++++++++++++ src/experimental/assoc.scad | 9 +++++++++ 2 files changed, 23 insertions(+) create mode 100644 src/experimental/_impl/_assoc_impl.scad create mode 100644 src/experimental/assoc.scad diff --git a/src/experimental/_impl/_assoc_impl.scad b/src/experimental/_impl/_assoc_impl.scad new file mode 100644 index 00000000..705367f6 --- /dev/null +++ b/src/experimental/_impl/_assoc_impl.scad @@ -0,0 +1,14 @@ +use ; + +function _assoc_get(array, key) = + let(idx = search([key], array)[0]) + array[idx][1]; + +function _assoc_put(array, key, value) = + let(idx = search([key], array)[0]) + idx == [] ? concat(array, [[key, value]]) : + concat(slice(array, 0, idx), [[key, value]], slice(array, idx + 1)); + +function _assoc_remove(array, key) = + let(idx = search([key], array)[0]) + idx == [] ? array : concat(slice(array, 0, idx), slice(array, idx + 1)); \ No newline at end of file diff --git a/src/experimental/assoc.scad b/src/experimental/assoc.scad new file mode 100644 index 00000000..04b6cc88 --- /dev/null +++ b/src/experimental/assoc.scad @@ -0,0 +1,9 @@ +use ; + +// treat an associative array as a dictionary. + +function assoc(array, cmd, key, value) = + is_undef(array) ? [] : + cmd == "put" ? _assoc_put(array, key, value) : + cmd == "get" ? _assoc_get(array, key) : + cmd == "remove" ? _assoc_remove(array, key) : assert("Uknown command"); \ No newline at end of file