This library is for annotating functions using Refract. The idea is the provide types for both the inputs and outputs for a given function and check those types when the function is executed.
This library is a plugin for Minim and requires Minim to be installed.
npm install minim-typedThis plugin is loaded like any Minim plugin would be loaded.
var minim = require('minim');
var minimTyped = require('minim-typed');
// Load the plugin
var namespace = minim.namespace().use(minimTyped);All functions for typed Minim are added to the namespace instance.
The default function is the identity function. This means if you want to check the type of a value, you need to annotate both the input and output of that value as being the same type. Once this is done, you can check the type of simple values.
var stringChecker = namespace.typed.build({
// string -> string
annotations: [
annotate('string'),
annotate('string'),
],
});
stringChecker('foobar'); // Returns 'foobar'
stringChecker(1000); // Throws TypeErrorTyped Minim is only used for annotating functions, and though the identity function is default, you may provide any function you like.
var sum = namespace.typed.build({
// array[number] -> number
annotations: [
annotate('array', [annotate('number')]),
annotate('number'),
],
fn: function(numbers) {
return numbers.reduce(function(total, number) {
return total + number;
});
},
});
sum([1, 2, 3]); // Returns 6
sum(['a', 'b', 'c']); // Throws TypeErrorThis solves question one of Project Euler with typed functions.
Find the sum of all the multiples of 3 or 5 below 1000.
var _ = require('lodash');
var minim = require('minim');
var minimTyped = require('minim-typed');
var annotate = require('minim-typed').annotate;
var namespace = minim.namespace().use(minimTyped);
var divBy = namespace.typed.build({
// number number -> boolean
annotations: [
annotate('string'),
annotate('string'),
annotate('boolean'),
],
fn: function(x, y) { return (x % y) === 0; }
});
var divBy3or5 = namespace.typed.build({
// number -> boolean
annotations: [
annotate('number'),
annotate('boolean'),
],
fn: function(x) {
var result = divBy(x, 3) || divBy(x, 5);
return result;
}
});
var sum = namespace.typed.build({
// array[number] -> number
annotations: [
annotate('array', [annotate('number')]),
annotate('number'),
],
fn: function(numbers) {
return numbers.reduce(function(total, number) {
return total + number;
});
}
});
var take = namespace.typed.build({
// number -> array
annotations: [
annotate('number'),
annotate('array'),
],
// Just wrapping Lodash's range function
fn: _.range
});
var answer = sum(take(1000).filter(function(number) {
return divBy3or5(number)
}));
console.log(answer);This code is licensed under the MIT license.