Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add '-sort-keyed'. #166

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
26 changes: 26 additions & 0 deletions dash.el
Expand Up @@ -1888,6 +1888,32 @@ if the first element should sort before the second."
(declare (debug (form form)))
`(-sort (lambda (it other) ,form) ,list))

(defun -sort-keyed (key-computer comparator list)
"Sort LIST by given keys, comparing them using COMPARATOR.
First KEY-COMPUTER is used to compute key value for each list
item. Then resulting keys are sorted (stably) according to
COMPARATOR. Finally, a copy of the original LIST is built and
rearranged in the same way.

LIST is not modified by side effects. KEY-COMPARATOR is called
once for each element of LIST, i.e. with one argument.
COMPARATOR is called with two keys, and should return non-nil if
the first one (and thus its associated LIST element) should sort
before the second."
(if (cdr list)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this really necessary? Map and sort on empty list returns nil, so that's not a problem, and while calling it on a list with length one is pointless, the performance hit is so negigible it is not worth the extra complexity.

;; We don't use '-sort' because there's no need to copy
;; argument.
(-map 'cdr
(sort (--map (cons (funcall key-computer it) it) list)
(lambda (a b) (funcall comparator (car a) (car b)))))
(when list
(list (car list)))))

(defmacro --sort-keyed (key-form comparator-form list)
"Anaphoric form of `-sort-keyed'."
(declare (debug (form form form)))
`(-sort-keyed (lambda (it) ,key-form) (lambda (it other) ,comparator-form) ,list))

(defun -list (&rest args)
"Return a list with ARGS.

Expand Down