diff --git a/kiss/src/kiss/Kiss.hx b/kiss/src/kiss/Kiss.hx index bd3c5210..af712a13 100644 --- a/kiss/src/kiss/Kiss.hx +++ b/kiss/src/kiss/Kiss.hx @@ -50,7 +50,7 @@ class Kiss { // Helpful aliases k.defAlias("print", Symbol("Prelude.print")); k.defAlias("groups", Symbol("Prelude.groups")); - + k.defAlias("zip", Symbol("Prelude.zip")); 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/kiss/src/kiss/Prelude.hx b/kiss/src/kiss/Prelude.hx index 79c6c8bf..9976a162 100644 --- a/kiss/src/kiss/Prelude.hx +++ b/kiss/src/kiss/Prelude.hx @@ -158,6 +158,34 @@ class Prelude { return fullGroups; } + public static function zip(a:Array, b:Array, extraHandling = Drop):Array> { + var max = Math.floor(if (a.length != b.length) { + switch (extraHandling) { + case Throw: + throw 'zip was given lists of mis-matched size: $a, $b'; + case Keep: + Math.max(a.length, b.length); + case Drop: + Math.min(a.length, b.length); + } + } else { + a.length; + }); + + return [ + for (idx in 0...max) [ + if (idx < a.length) + a[idx] + else + null, + if (idx < b.length) + b[idx] + else + null + ] + ]; + } + public static dynamic function truthy(v:Any) { return switch (Type.typeof(v)) { case TNull: false; diff --git a/kiss/src/test/cases/BasicTestCase.hx b/kiss/src/test/cases/BasicTestCase.hx index 0e3d8f2a..d76682b7 100644 --- a/kiss/src/test/cases/BasicTestCase.hx +++ b/kiss/src/test/cases/BasicTestCase.hx @@ -136,8 +136,11 @@ class BasicTestCase extends Test { } function testGroups() { - Assert.equals([[1, 2], [3, 4]].toString(), BasicTestCase.myGroups1().toString()); - Assert.equals([[1, 2, 3], [4]].toString(), BasicTestCase.myGroups2().toString()); + _testGroups(); + } + + function testZip() { + _testZip(); } function testLet() { diff --git a/kiss/src/test/cases/BasicTestCase.kiss b/kiss/src/test/cases/BasicTestCase.kiss index 4326d72a..4683090a 100644 --- a/kiss/src/test/cases/BasicTestCase.kiss +++ b/kiss/src/test/cases/BasicTestCase.kiss @@ -114,11 +114,20 @@ (defun myTypeCheck [] (the Int 5)) -(defun myGroups1 [] - (groups [1 2 3 4] 2)) +(defun _testGroups [] + (Assert.equals (.toString [[1 2] [3 4]]) (.toString (groups [1 2 3 4] 2))) + (Assert.equals (.toString [[1 2 3] [4]]) (.toString (groups [1 2 3 4] 3 Keep))) + (try (begin (groups [1 2 3 4] 3 Throw) (Assert.fail)) + (catch [error] (Assert.pass)))) -(defun myGroups2 [] - (groups [1 2 3 4] 3 Keep)) +(defun _testZip [] + (Assert.equals (.toString [[1 2] [3 4]]) (.toString (zip [1 3] [2 4] Throw))) + (Assert.equals (.toString [[1 2] [3 null]]) (.toString (zip [1 3] [2] Keep))) + (Assert.equals (.toString [[1 2] [null 4]]) (.toString (zip [1 null] [2 4] Keep))) + (try (begin (zip [1 3] [2] Throw) (Assert.fail)) + (catch [error] (Assert.pass))) + (try (begin (zip [1] [2 4] Throw) (Assert.fail)) + (catch [error] (Assert.pass)))) (defun _testLet [] (let [a 5