diff --git a/dash.el b/dash.el index 9d366ff5..1c895bfd 100644 --- a/dash.el +++ b/dash.el @@ -881,6 +881,23 @@ See also: `-splice', `-splice-list'" (let ((split-list (-split-at n list))) (nconc (car split-list) (cons x (cadr split-list))))) +(defun -insert-sorted (comparator item list) + "Using COMPARATOR insert ITEM into sorted LIST. + +It is assumed that LIST is already sorted on input. + +The new item is inserted at the first position where + + (funcall comparator x item) + +returns nil. X is the \"current\" item from the input list." + (let ((place (-split-with (lambda (x) (funcall comparator x item)) list))) + (-concat (car place) (list item) (cadr place)))) + +(defmacro --insert-sorted (form item list) + "Anaphoric form of `-insert-sorted'." + `(-insert-sorted (lambda (it other) ,form) ,list)) + (defun -replace-at (n x list) "Return a list with element at Nth position in LIST replaced with X. @@ -2640,6 +2657,8 @@ structure such as plist or alist." "-split-at" "-rotate" "-insert-at" + "-insert-sorted" + "--insert-sorted" "-replace-at" "-update-at" "--update-at" diff --git a/dev/examples.el b/dev/examples.el index 37c1fd92..a1d26049 100644 --- a/dev/examples.el +++ b/dev/examples.el @@ -256,6 +256,13 @@ new list." (-insert-at 1 'x '(a b c)) => '(a x b c) (-insert-at 12 'x '(a b c)) => '(a b c x)) + (defexamples -insert-sorted + (-insert-sorted '< 4 '(1 2 3 5 6 7)) => '(1 2 3 4 5 6 7) + (-insert-sorted (lambda (a b) (< (car a) (car b))) '(3 . "new") '((1) (2) (3 . "old"))) => '((1) (2) (3 . "new") (3 . "old")) + (-insert-sorted '< 1 '(2 3 5 6 7)) => '(1 2 3 5 6 7) + (-insert-sorted '< 8 '(2 3 5 6 7)) => '(2 3 5 6 7 8) + (-insert-sorted '< 1 nil) => '(1)) + (defexamples -replace-at (-replace-at 0 9 '(0 1 2 3 4 5)) => '(9 1 2 3 4 5) (-replace-at 1 9 '(0 1 2 3 4 5)) => '(0 9 2 3 4 5)