Comment Comment by mpfundstein Shameless plug but here is my pattern machter [1] :DExample: // simple factorial const factorial = n => match(n) .when(0, 1) .otherwise(n => n * factorial(n - 1)); // walking a tree class Tree { constructor(left, right) { this.left = left; this.right = right; } } class Node { constructor(value) { this.value = value; } } const T = (l, r) => new Tree(l, r); const N = v => new Node(v); const walkT = t => match(t) .when(Node, v => console.log(v.value)) .when(Tree, t => { walkT(t.left); walkT(t.right)}) .otherwise(_ => 'error'); const mapT = (f, t) => match(t) .when(Node, v => N(f(v.value))) .when(Tree, t => T(mapT(f, t.left), mapT(f, t.right))) .otherwise(_ => { throw new Error('error') }); Works also on deeply nested objects.[1] https://github.com/MarkusPfundstein/pmatch-js parent mpfundstein 8 years ago
Example:
Works also on deeply nested objects.[1] https://github.com/MarkusPfundstein/pmatch-js