From 5417b512e77a7434f7b1fc9d55035921725a8df1 Mon Sep 17 00:00:00 2001 From: William Carroll Date: Mon, 1 Aug 2022 13:43:34 -0700 Subject: feat(wpcarro/emacs): Support list-chunk function Would be nice to remove the top-level `if` statement, but I can't be bothered to debug the first unit test without that workaround. Change-Id: I4ba576bda915eeb11f9fbfeb5d95d8e5668fd0bd Reviewed-on: https://cl.tvl.fyi/c/depot/+/6022 Reviewed-by: wpcarro Autosubmit: wpcarro Tested-by: BuildkiteCI --- users/wpcarro/emacs/pkgs/list/list.el | 18 ++++++++++++++++++ users/wpcarro/emacs/pkgs/list/tests.el | 10 ++++++++++ 2 files changed, 28 insertions(+) (limited to 'users/wpcarro') diff --git a/users/wpcarro/emacs/pkgs/list/list.el b/users/wpcarro/emacs/pkgs/list/list.el index 03382991e035..a1822e77ff60 100644 --- a/users/wpcarro/emacs/pkgs/list/list.el +++ b/users/wpcarro/emacs/pkgs/list/list.el @@ -160,6 +160,24 @@ (list-cons x acc))) xs))) +(defun list-chunk (n xs) + "Chunk XS into lists of size N." + (if (> n (length xs)) + (list xs) + (->> xs + (list-reduce '(:curr () :result ()) + (lambda (x acc) + (let ((curr (plist-get acc :curr)) + (result (plist-get acc :result))) + (if (= (- n 1) (length curr)) + `(:curr () :result ,(list-cons (list-reverse (list-cons x curr)) result)) + `(:curr ,(list-cons x curr) :result ,result))))) + (funcall (lambda (xs) + (let ((curr (plist-get xs :curr)) + (result (plist-get xs :result))) + (if curr (list-cons curr result)) result))) + list-reverse))) + ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Predicates ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; diff --git a/users/wpcarro/emacs/pkgs/list/tests.el b/users/wpcarro/emacs/pkgs/list/tests.el index abba6b59d62f..a6096a1d6e92 100644 --- a/users/wpcarro/emacs/pkgs/list/tests.el +++ b/users/wpcarro/emacs/pkgs/list/tests.el @@ -42,3 +42,13 @@ (ert-deftest list-join () (should (equal "foo-bar-baz" (list-join "-" '("foo" "bar" "baz"))))) + +(ert-deftest list-chunk () + (should (equal '((1 2 3 4 5 6)) + (list-chunk 7 '(1 2 3 4 5 6)))) + (should (equal '((1) (2) (3) (4) (5) (6)) + (list-chunk 1 '(1 2 3 4 5 6)))) + (should (equal '((1 2 3) (4 5 6)) + (list-chunk 3 '(1 2 3 4 5 6)))) + (should (equal '((1 2) (3 4) (5 6)) + (list-chunk 2 '(1 2 3 4 5 6))))) -- cgit 1.4.1