Книга: Functional Programming in JavaScript
Назад: Functors
Дальше: Arrays and functors

Creating functors

It turns out we already have one functor: . It grabs the values within the container, an array, and applies a function to it.

[1, 4, 9].map(Math.sqrt); // Returns: [1, 2, 3]

However, we'll need to write it as a global function and not as a method of the array object. This will allow us to write cleaner, safer code later on.

// map :: (a -> b) -> [a] -> [b] var map = function(f, a) {   return arr(a).map(func(f)); }

This example seems like a contrived wrapper because we're just piggybacking onto the function. But it serves a purpose. It provides a template for maps of other types.

// strmap :: (str -> str) -> str -> str var strmap = function(f, s) {   return str(s).split('').map(func(f)).join(''); }  // MyObject#map :: (myValue -> a) -> a MyObject.prototype.map(f{   return func(f)(this.myValue); }
Назад: Functors
Дальше: Arrays and functors

bsn
thank
Vesa Karvonen
I hope you don't mind, but I’d like to point you and your readers to my high-performance optics library for JavaScript that is in production use in multiple projects, has comprehensive support for partial optics and interactive documentation: https://calmm-js.github.io/partial.lenses/ (this takes a moment to load — be patient!)