From be7032ad2b30e9b868bbec039ccdb743dc901fdc Mon Sep 17 00:00:00 2001 From: Jichao Ouyang Date: Wed, 11 May 2016 23:23:44 +0800 Subject: [PATCH] A handy ListOf Type simple ListOf[T] Type as mention in #32 validate it is a Array and each element type to be T --- test/index.js | 12 ++++++++++++ union-type.js | 15 +++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/test/index.js b/test/index.js index d3f83d1..1abd32a 100644 --- a/test/index.js +++ b/test/index.js @@ -61,6 +61,18 @@ describe('union type', function() { }, /wrong value/); }); }); + it('array of types', function() { + var Point = Type({Point: [Number, Number]}); + var Shape = Type({Shape: [Type.ListOf(Point)]}).Shape; + assert.throws(function(){ + Shape([1,Point.Point(1,2),3]); + }, /wrong value/); + assert.throws(function(){ + Shape([Point.Point(1,2), Point.Point('3',1)]); + }, /wrong value/) + Shape([Point.Point(1,2), Point.Point(1,2), Point.Point(1,2)]); + Shape([]); + }); it('nest types', function() { var Point = Type({Point: [isNumber, isNumber]}); var Shape = Type({Circle: [Number, Point], diff --git a/union-type.js b/union-type.js index 76b59e0..5449faf 100644 --- a/union-type.js +++ b/union-type.js @@ -127,4 +127,19 @@ function Type(desc) { Type.check = true; +Type.ListOf = function (T) { + var ListOf = Type({List:[Array], HeadTail:[T, Array]}); + var validate = ListOf.case({ + List: function (array) { + return array.length == 0 || validate(ListOf.HeadTail(array[0],array.slice(1))); + }, + HeadTail: function (head, tail) { + return tail.slice(1).length == 0 || validate(ListOf.HeadTail(tail[0], tail.slice(1))); + } + }); + return function(array) { + return validate(ListOf.List(array)); + } +} + module.exports = Type;