DEV Community

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

Posted on

4 3

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

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️