From 609f14656a0d74bb6244cf2f326c6d563094172f Mon Sep 17 00:00:00 2001 From: Nat Quayle Nelson Date: Sat, 5 Dec 2020 18:46:24 -0700 Subject: [PATCH] Improve (groups) --- src/kiss/Kiss.hx | 2 ++ src/kiss/Prelude.hx | 20 +++++++++++++++++--- src/test/cases/BasicTestCase.kiss | 4 ++-- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/src/kiss/Kiss.hx b/src/kiss/Kiss.hx index c06372f..bd3c521 100644 --- a/src/kiss/Kiss.hx +++ b/src/kiss/Kiss.hx @@ -49,6 +49,8 @@ class Kiss { // Helpful aliases k.defAlias("print", Symbol("Prelude.print")); + k.defAlias("groups", Symbol("Prelude.groups")); + k.defAlias("map", Symbol("Lambda.map")); k.defAlias("filter", Symbol("Lambda.filter")); // TODO use truthy as the default filter function k.defAlias("has", Symbol("Lambda.has")); diff --git a/src/kiss/Prelude.hx b/src/kiss/Prelude.hx index 1f3f275..79c6c8b 100644 --- a/src/kiss/Prelude.hx +++ b/src/kiss/Prelude.hx @@ -5,6 +5,13 @@ using Std; import kiss.Operand; import haxe.ds.Either; +/** What functions that process Lists should do when there are more elements than expected **/ +enum ExtraElementHandling { + Keep; // Keep the extra elements + Drop; // Drop the extra elements + Throw; // Throw an error +} + class Prelude { static function variadic(op:(Operand, Operand) -> Null, comparison = false):(Array) -> Dynamic { return (l:kiss.List) -> switch (Lambda.fold(l.slice(1), op, l[0])) { @@ -129,7 +136,7 @@ class Prelude { public static var areEqual = variadic(_areEqual, true); - public static function groups(a:Array, size, keepRemainder = false) { + public static function groups(a:Array, size, extraHandling = Drop) { var numFullGroups = Math.floor(a.length / size); var fullGroups = [ for (num in 0...numFullGroups) { @@ -138,9 +145,16 @@ class Prelude { a.slice(start, end); } ]; - if (a.length % size != 0 && keepRemainder) { - fullGroups.push(a.slice(numFullGroups * size)); + if (a.length % size != 0) { + switch (extraHandling) { + case Throw: + throw 'groups was given a non-divisible number of elements: $a, $size'; + case Keep: + fullGroups.push(a.slice(numFullGroups * size)); + case Drop: + } } + return fullGroups; } diff --git a/src/test/cases/BasicTestCase.kiss b/src/test/cases/BasicTestCase.kiss index 3aca019..4326d72 100644 --- a/src/test/cases/BasicTestCase.kiss +++ b/src/test/cases/BasicTestCase.kiss @@ -115,10 +115,10 @@ (the Int 5)) (defun myGroups1 [] - (Prelude.groups [1 2 3 4] 2)) + (groups [1 2 3 4] 2)) (defun myGroups2 [] - (Prelude.groups [1 2 3 4] 3 true)) + (groups [1 2 3 4] 3 Keep)) (defun _testLet [] (let [a 5