Skip to content

Commit

Permalink
A handy ListOf Type
Browse files Browse the repository at this point in the history
simple ListOf[T] Type as mention in paldepind#32

validate it is a Array and each element type to be T
  • Loading branch information
jcouyang committed May 11, 2016
1 parent 92804d4 commit be7032a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
12 changes: 12 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand Down
15 changes: 15 additions & 0 deletions union-type.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;

0 comments on commit be7032a

Please sign in to comment.