]> code.delx.au - gnu-emacs/commitdiff
Do not signal an error when trying to delete a key from an array
authorNicolas Petton <nicolas@petton.fr>
Fri, 24 Apr 2015 17:29:59 +0000 (19:29 +0200)
committerNicolas Petton <nicolas@petton.fr>
Fri, 24 Apr 2015 17:29:59 +0000 (19:29 +0200)
* lisp/emacs-lisp/map.el (map-delete): When map is an array, check if
the key is present to avoid signaling an error.

* test/automated/map-tests.el: Add a test for deleting non-existing
keys from maps.

lisp/emacs-lisp/map.el
test/automated/map-tests.el

index 621c37f2b76cec38395679547aff946a3062e82c..087ab286ac33d1dbe94ed00af37eeab13904636f 100644 (file)
@@ -73,7 +73,7 @@ If MAP is an array, store nil at the index KEY."
      (map--dispatch (m ,map m)
        :list (setq ,map (map--delete-alist m ,key))
        :hash-table (remhash ,key m)
-       :array (aset m ,key nil))))
+       :array (map--delete-array m ,key))))
 
 (defun map-nested-elt (map keys &optional default)
   "Travserse MAP using KEYS and return the looked up value or DEFAULT if nil.
@@ -261,13 +261,20 @@ form.
              (seq-elt map key))
         default)))
 
-
 (defun map--delete-alist (map key)
   "Return MAP with KEY removed."
   (seq-remove (lambda (pair)
                 (equal key (car pair)))
               map))
 
+(defun map--delete-array (map key)
+  "Set nil in the array MAP at the index KEY if present and return MAP."
+  (let ((len (seq-length map)))
+    (and (>= key 0)
+         (<= key len)
+         (aset m key nil)))
+  map)
+
 (defun map--into-hash-table (map)
   "Convert MAP into a hash-table."
   (let ((ht (make-hash-table :size (map-length map)
index f41cd70c4c55c4ebb5e16e677a2daff81ee994ba..5201116613e29d15036cf5a926811c490a917aa5 100644 (file)
@@ -96,7 +96,10 @@ Evaluate BODY for each created map.
 (ert-deftest test-map-delete ()
   (with-maps-do map
     (map-delete map 1)
-    (assert (null (map-elt map 1)))))
+    (assert (null (map-elt map 1))))
+  (with-maps-do map
+    (map-delete map -2)
+    (assert (null (map-elt map -2)))))
 
 (ert-deftest test-map-delete-return-value ()
   (let ((ht (make-hash-table)))