Prelude.groups()

This commit is contained in:
2020-11-19 12:48:22 -07:00
parent 2308fd8635
commit 8ee2fa5bca
3 changed files with 27 additions and 1 deletions

View File

@@ -45,6 +45,21 @@ class Prelude {
return if (a == b) a else Math.NaN;
}
public static function groups<T>(a:Array<T>, 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) {

View File

@@ -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());
}
}

View File

@@ -86,3 +86,9 @@
(defun myTypeCheck []
(the Int 5))
(defun myGroups1 []
(Prelude.groups [1 2 3 4] 2))
(defun myGroups2 []
(Prelude.groups [1 2 3 4] 3 true))