|
|
|
|
|
by mpfundstein
2985 days ago
|
|
Shameless plug but here is my pattern machter [1] :D Example: // 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 |
|