Classes in JavaScript are quite awkward. Fortunately there's another way for polymorphism: Multimethods. They allow dispatching on more than one argument. You can think of them as
"switch statement on steroids"... only better, because they can be extended at runtime.
Multimethods are methods that don't belong to classes; therefore there's no need to trap
your data inside of classes.
Function some(collection, fn) iterates a collection. It returns true if some the
callback function fn returns true for one of the items in the collection and breaks
the iteration in this case. If the callback returns false for all the items, some
returns false.
console.log(isA(0.5, t_integer));// false: doesn't match t_integer's predicate
// So far this didn't really use the hierarchical aspect much.
// Let's make the relationship established by derive show:
var vehicle =type();// No predicate: vehicle is an "abstract" base type
var car =type({wheels: t_integer});// Matching a schema
console.log(isA(car, vehicle));// false: not related yet
console.log(isA({wheels:4}, vehicle));// false: not related yet
console.log(isA({wheels:4}, car));// true: matched by schema
derive(car, vehicle);// now car's a vehicle
console.log(isA({wheels:4}, vehicle));// true: it's a car, so it's a vehicle
console.log(isA(car, vehicle));// true: type car's a subtype of vehicle
});
Schema validators
In ENJOY.js, validating data can be done by using either the valid(data, schema) function
or by creating a validator with the validator(schema) function and then using the resulting
function to check the data.
ENJOY's isA(a, t) function and the type(checker) function are both able to be used with schemas.
Schemas can contain pure data, as well as predicate functions and types, which are used to validate
specific values in the data. This means the data may not include functions - but they shouldn't anyway.