Skip to content

Instantly share code, notes, and snippets.

@diasbruno
Created May 13, 2021 15:26
Show Gist options
  • Save diasbruno/289bd58a38cf450566fbd9197496012c to your computer and use it in GitHub Desktop.
Save diasbruno/289bd58a38cf450566fbd9197496012c to your computer and use it in GitHub Desktop.
Deriving everything with reduce - Stack meeting at Snowman Labs
// Derivação de `map` com `reduce`.
> f = item => item + 2;
[Function: f]
> [1, 2, 3, 4].reduce((acc, item) => { acc.push(f(item)); return acc; }, []);
[ 3, 4, 5, 6 ]
> [1, 2, 3, 4].map(f);
[ 3, 4, 5, 6 ]
// Reduzindo com outros acumuladores.
> [1, 2, 3, 4].reduce((acc, item) => { acc[item] = f(item); return acc; }, {});
{ '1': 3, '2': 4, '3': 5, '4': 6 }
// Implementação de `map` no objeto `Identidade`.
> function Id(x) { this.x = x; }
> Id.prototype.map = function(f) { return new Id(f(this.x)); }
[Function (anonymous)]
> (new Id(1)).map(f)
Id { x: 3 }
> ([1]).map(f)
[ 3 ]
// Derivando `filter` com reduce.
> pred = x => x > 2;
> [1, 2, 3, 4].reduce((acc, item) => { (pred(item) && acc.push(item)); return acc; }, []);
[ 3, 4 ]
// Implementação do `reduce` em outras classes.
> Id.prototype.reduce = function(f, acc) { return f(acc, this.x); }
[Function (anonymous)]
> (new Id(1)).reduce((acc, item) => acc + item, 0)
1
> (new Id(1)).reduce((acc, item) => acc + item, 1)
2
> (new Id(1)).reduce((acc, item) => acc + item, 2)
3
> (new Id(1)).reduce((acc, item) => acc.x + item, new Id(0))
1
> (new Id(1)).reduce((acc, item) => new Id(acc.x + item), new Id(0))
Id { x: 1 }
> (new Id(1)).reduce((acc, item) => new Id(acc.x + item), new Id(1))
Id { x: 2 }
> (new Id(1)).reduce((acc, item) => new Id(acc.x + item), new Id(2))
Id { x: 3 }
> (new Id(1)).reduce((acc, item) => new Id(acc.x + item), new Id(3))
Id { x: 4 }
> (new Id(1)).reduce((acc, item) => new Id(acc.x + item), new Id(4))
Id { x: 5 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment