From 946378510f1dd542cc2f30efe22a16da69749840 Mon Sep 17 00:00:00 2001 From: Andrey Orst Date: Thu, 29 Oct 2020 19:55:31 +0300 Subject: feature: functions to access table values --- core.fnl | 20 ++++++++++++++++++++ core_test.fnl | 20 +++++++++++++++++++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/core.fnl b/core.fnl index b993863..d151c77 100644 --- a/core.fnl +++ b/core.fnl @@ -397,4 +397,24 @@ oppisite truth value." (set (i k) (next kvs i))) tbl)) +(fn& core.get + "Get value from the table by accessing it with a `key'. +Accepts additional `not-found' as a marker to return if value wasn't +found in the table." + ([tbl key] (get tbl key nil)) + ([tbl key not-found] + (if-some [res (. tbl key)] + res + not-found))) + +(fn& core.get-in + "Get value from nested set of tables by providing key sequence. +Accepts additional `not-found' as a marker to return if value wasn't +found in the table." + ([tbl keys] (get-in tbl keys nil)) + ([tbl keys not-found] + (if-some [res (. tbl (. keys 1))] + (get-in tbl [(unpack tbl 2)] not-found) + not-found))) + core diff --git a/core_test.fnl b/core_test.fnl index 9b0359c..d607935 100644 --- a/core_test.fnl +++ b/core_test.fnl @@ -46,7 +46,9 @@ : reverse : inc : dec - : assoc} + : assoc + : get + : get-in} (require :core)) (deftest equality @@ -425,3 +427,19 @@ (testing dec (assert-eq (dec 1) 0) (assert-eq (dec -1) -2))) + +(deftest table-access + (testing get + (assert-eq (get {:key1 10 :key2 20} :key1) 10) + (assert-eq (get {:key1 10 :key2 20} :key1 false) 10) + (assert-eq (get {:key1 10 :key2 20} :key3 false) false) + (assert-eq (get {:key1 10 :key2 20} :key3) nil)) + + (testing get + (local t {:a {:b {:c 10}}}) + (assert-eq (get t [:a]) {:b {:c 10}}) + (assert-eq (get t [:a :b]) {:c 10}) + (assert-eq (get t [:a :b :c]) 10) + (assert-eq (get t [:a :b :c] false) 10) + (assert-eq (get t [:a :b :d] false) false) + (assert-eq (get t [:a :b :d]) nil))) -- cgit v1.2.3