Skip to content

Commit

Permalink
Add -insert-sorted
Browse files Browse the repository at this point in the history
  • Loading branch information
Fuco1 committed Mar 13, 2018
1 parent 87d5fea commit f2a7e2d
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
19 changes: 19 additions & 0 deletions dash.el
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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"
Expand Down
7 changes: 7 additions & 0 deletions dev/examples.el
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit f2a7e2d

Please sign in to comment.