liveBook · Manning

Functor

As explained in The Joy of JavaScript

A functor is a structure or abstraction that provides a mapping operation over contained values while preserving the surrounding structure.

A functor is a value-containing structure with a map operation. Map applies a function to the contained value and returns a structure of the expected type. JavaScript arrays offer a familiar example: mapping transforms their elements and produces another array. The same interface can make custom objects participate in function-composition pipelines. section 5.4.1 section 5.4

A custom map should obey two rules:

  • Identity: mapping the identity function leaves the contained value equivalent, inside a new container of the same type. section 5.4.1
  • Composition: mapping one function and then another is equivalent to mapping their composition. section 5.4.1

A reusable map

An Id container can provide `of(value)` to wrap a value and `get()` to retrieve it. A Functor mixin then defines `map(f = identity) { return this.constructor.of(f(this.get())); }`. Thus `Id.of('aabbcc').map(unique).map(join).map(toUpper).get()` yields `'ABC'`. Each map creates another Id, so transformations remain chainable without changing the original container. section 5.4.1 section 1.3

Map can also express conditional processing. With a Validation type, Success maps a transformation over its value, while Failure skips it; both branches retain a composable interface. If a mapped function itself returns a container, ordinary map can produce nested containers. A monad adds flatMap for that case. section 5.5.4 section 5.4.2

A shared map contract lets standalone functions from Ramda delegate to custom objects. For implementations where the resulting constructor matters, `Symbol.species` can document and select the type produced by map. section 5.5.8 section 7.5.3

How The Joy of JavaScript covers it

How deep it goes
Defines map through identity and composition rules, then implements a reusable mixin; defers extensive algebraic theory.
Examples
Demonstrates array mapping, an Id transformation pipeline, and Success/Failure branches that run or skip mapped functions.
What it assumes
Assumes familiarity with JavaScript functions and composition, but requires no category-theory background.
What you can do after
Build it from scratch with an Id-style container and map mixin, then apply the contract to conditional validation.
How it connects
Connects functors to function composition, monads, algebraic data types, and Symbol.species.

Also explained in

Compare how 6 books explain functor →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Joy of JavaScript. The section links point to the parts of the book it draws on.