From 6b3f4113cc6ffe79eff0fa0008a1d8d95f5a6bac Mon Sep 17 00:00:00 2001 From: William Carroll Date: Fri, 29 Jul 2022 18:12:16 -0700 Subject: feat(wpcarro/emacs): Support default value for al-get Similar to Elixir's `Map.get/3`. Change-Id: I736f7e618aafc786a32eeba46ca635cb27db18b6 Reviewed-on: https://cl.tvl.fyi/c/depot/+/6000 Reviewed-by: wpcarro Autosubmit: wpcarro Tested-by: BuildkiteCI --- users/wpcarro/emacs/pkgs/al/al.el | 8 +++++--- users/wpcarro/emacs/pkgs/al/tests.el | 13 +++++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/users/wpcarro/emacs/pkgs/al/al.el b/users/wpcarro/emacs/pkgs/al/al.el index aa81894153..4c37526c64 100644 --- a/users/wpcarro/emacs/pkgs/al/al.el +++ b/users/wpcarro/emacs/pkgs/al/al.el @@ -111,10 +111,12 @@ Note that this doesn't append to the alist in the way that most alists handle (map-put! xs k v)) ;; Read -(defun al-get (k xs) - "Return the value at K in XS; otherwise, return nil. +(defun al-get (k xs &optional default) + "Return the value at K in XS; otherwise, return nil or DEFAULT (if set). Returns the first occurrence of K in XS since alists support multiple entries." - (cdr (assoc k xs))) + (if (not (al-has-key? k xs)) + default + (cdr (assoc k xs)))) (defun al-get-entry (k xs) "Return the first key-value pair at K in XS." diff --git a/users/wpcarro/emacs/pkgs/al/tests.el b/users/wpcarro/emacs/pkgs/al/tests.el index 5146ee6b21..6556ddabc3 100644 --- a/users/wpcarro/emacs/pkgs/al/tests.el +++ b/users/wpcarro/emacs/pkgs/al/tests.el @@ -14,6 +14,19 @@ (al-has-key? 'fname '((fname . "William"))) (not (al-has-key? 'lname '((fname . "William")))))) +(ert-deftest al-get () + (let ((xs (->> (al-new) + (al-set 'fname "John") + (al-set 'employed? nil)))) + (and + (string= "John" (al-get 'fname xs)) + (string= "Cleese" (al-get 'lname xs "Cleese")) + ;; Test that the value of nil is returned even when a default is defined, + ;; which could be a subtle bug in the typical Elisp pattern of supporting + ;; defaults with: (or foo default). + (eq nil (al-get 'employed? xs)) + (eq nil (al-get 'employed? xs "default"))))) + (ert-deftest al-has-value? () (and (al-has-value? "William" '((fname . "William"))) -- cgit 1.4.1