From 8ee2fa5bca6f23f9ef9398a5a93f5fc991cbb01d Mon Sep 17 00:00:00 2001 From: Nat Quayle Nelson Date: Thu, 19 Nov 2020 12:48:22 -0700 Subject: [PATCH] Prelude.groups() --- src/kiss/Prelude.hx | 15 +++++++++++++++ src/test/cases/BasicTestCase.hx | 5 +++++ src/test/cases/BasicTestCase.kiss | 8 +++++++- 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/kiss/Prelude.hx b/src/kiss/Prelude.hx index 894d794b..cfb49542 100644 --- a/src/kiss/Prelude.hx +++ b/src/kiss/Prelude.hx @@ -45,6 +45,21 @@ class Prelude { return if (a == b) a else Math.NaN; } + public static function groups(a:Array, size, keepRemainder = false) { + var numFullGroups = Math.floor(a.length / size); + var fullGroups = [ + for (num in 0...numFullGroups) { + var start = num * size; + var end = (num + 1) * size; + a.slice(start, end); + } + ]; + if (a.length % size != 0 && keepRemainder) { + fullGroups.push(a.slice(numFullGroups * size)); + } + return fullGroups; + } + // TODO put truthy in KissState // TODO make [] falsy public static dynamic function truthy(v:Any) { diff --git a/src/test/cases/BasicTestCase.hx b/src/test/cases/BasicTestCase.hx index 52ad5f81..323c2434 100644 --- a/src/test/cases/BasicTestCase.hx +++ b/src/test/cases/BasicTestCase.hx @@ -141,4 +141,9 @@ class BasicTestCase extends Test { function testTypeCheck() { Assert.equals(5, BasicTestCase.myTypeCheck()); } + + function testGroups() { + Assert.equals([[1, 2], [3, 4]].toString(), BasicTestCase.myGroups1().toString()); + Assert.equals([[1, 2, 3], [4]].toString(), BasicTestCase.myGroups2().toString()); + } } diff --git a/src/test/cases/BasicTestCase.kiss b/src/test/cases/BasicTestCase.kiss index 3cda7ab4..b23bc54f 100644 --- a/src/test/cases/BasicTestCase.kiss +++ b/src/test/cases/BasicTestCase.kiss @@ -85,4 +85,10 @@ (catch [error] 7))) (defun myTypeCheck [] - (the Int 5)) \ No newline at end of file + (the Int 5)) + +(defun myGroups1 [] + (Prelude.groups [1 2 3 4] 2)) + +(defun myGroups2 [] + (Prelude.groups [1 2 3 4] 3 true)) \ No newline at end of file