DEV Community

Cover image for Functor's flavor in JS
Marcos Henrique
Marcos Henrique

Posted on

Functor's flavor in JS

There's no secret it's just mystery, straight to the point without hysteria ✨🔮

Basically it is a wrapper of a value, an object that encapsulates this value and implements the map () function.

An example as popular as Rock n Roll or Ronaldinho Gaúcho is the Array in JS, where it is a container (object) that contains a list of values or a dimensional and we have the map function that applies processing to these internal values, so much so that you launch a typeof [🦇, 🐙] will have an object as answer.

Creating your own functor

const secureType = value => ({
  value,
  map(fn) { 
    return secureType(fn(this.value))
  }
})

//using
const { value } = secureType('who\'s bad?')
  .map(text => text.toUpperCase())
  .map(text => `${text} 👹`)

console.log(value)
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
olavoparno profile image
Olavo Parno • Edited

HAHAHA awesome dude

const secureType = value => ({
value,
map(fn) {
console.log(this.value)
return secureType(fn(this.value))
}
})

// using
const { value } = secureType('who\'s bad?')
.map(text => text.toUpperCase())
.map(text => ${text} 👹)
.map(text => ${text} 👹)
.map(text => ${text} 👹)
.map(text => ${text} 👹)

Test