Last active
February 22, 2017 14:49
-
-
Save DrBoolean/ee644862f58c4539f371 to your computer and use it in GitHub Desktop.
JS array map via Comonad (https://gist.github.com/quelgar/4661081)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//https://gist.github.com/quelgar/4661081 | |
const daggy = require('daggy'); | |
const {range} = require('ramda'); | |
// type to hold an index and the array | |
const Pointer = daggy.tagged('i', 'a') | |
// Comonad instance | |
Pointer.prototype.extract = function() { return this.a[this.i] } | |
// builds a pointer of pointers where each element is focused. | |
Pointer.prototype.extend = function(f) { | |
return Pointer(this.i, range(0, this.a.length).map(i => f(Pointer(i, this.a)))) | |
} | |
const jsmap = (f, xs) => Pointer(0, xs).extend(({i: i, a: a}) => f(a[i], i, a)).a | |
// our map gets 3 args that are "context aware" - current el, index, and rest of the array | |
jsmap((e, i, xs) => e + i, [1,2,3,4,5]) | |
//=> [1,3,5,7,9] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment