links: [[Software Design Patterns MOC]]
---
# What is Functor
Functors are objects (Containers) that implement map method. These are the rules for a qualifying functor
1. Preserve function composition while mapping. It means composing two functions and then mapping the result function over a function should be the same as first mapping one function over the functor and then mapping the other one.
For example javascript Array's map method is a functor
```js
// fx.map(f).map(g) == fx.map(x => g(f(x)))
const result1 = ['Squirrels']
.map(s => s.substr(5))
.map(s => s.toUpperCase())
const result2 = ['Squirrels']
.map(s => s.substr(5).toUpperCase())
console.log(result1, result2)
```
2. If we map the **id** function over a functor, the functor that we get back should be the same as original functor
**id** is the identity function which just returns it's parameter unmodified.
```js
// fx.map(id) == id(fx)
const id = x => x
const result1 = ['Crayons'].map(id)
const result2 = id(['Crayons'])
console.log(result1, result2)
```
# Origin
In Mathematics, a **functor** is a map between categories. It belongs to a category theory in Mathematics.
---
tags: #design-pattern
sources:
- [Category theory](https://en.wikipedia.org/wiki/Category_theory)