Skip to content

Instantly share code, notes, and snippets.

@yelouafi
Created April 24, 2015 11:31
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yelouafi/c33e9b1baa9b069903bc to your computer and use it in GitHub Desktop.
Save yelouafi/c33e9b1baa9b069903bc to your computer and use it in GitHub Desktop.
Algebraic Data Types in javascript (see http://tech.pro/blog/6885/javascript-and-type-thinking)
function eachKey(obj, f) {
for(var key in obj) {
if( obj.hasOwnProperty(key) )
f(key, obj[key]);
}
}
function adtcase (base, proto, key) {
return (...args) => {
var inst = new base();
eachKey(proto(...args), (key, val) => { inst[key] = val })
inst['is'+key] = true;
return inst;
}
}
function adt(base, variants) {
eachKey(variants, (key, v) => {
if(typeof v === 'function')
base[key] = adtcase(base, v, key);
else {
base[key] = v;
v['is'+key] = true;
}
})
}
@mictian
Copy link

mictian commented Aug 9, 2015

Hi Yassine,
Great post!!

There is a minor details that I cannot understand. How is that a List end it up having the property isEmpty equals to true??
You use it en the rest of the function in your post, map, filter, etc.

Thank in advance!
Mictian

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment