DEV Community

Discussion on: Basic monads in Javascript

Collapse
 
edwilliams profile image
Ed Williams • Edited

This looks a excellent library; looking forward to using this. Could you help with the following example?

const data = [
  { wrongName: 'Jason', level: 7, cool: true },
  { wrongName: 'Blanche', level: 8, cool: false }
]

Maybe(data)
  .map(people => people.filter(person => person.cool))
  .map(people => people[0])
  .map(person => person.name)
  .map(name => name.toUpperCase())
  .cata({
    Just: data => console.log(data), // JASON
    Nothing: () => console.log('No data available')
  })

this appears to give me a Uncaught TypeError: Cannot read property 'toUpperCase'... but I imagined it might deal with the error in a similar way to Promises

Collapse
 
rametta profile image
Jason

For this example the following would be better if you weren't sure if some fields would be available

const data = [
  { wrongName: 'Jason', level: 7, cool: true },
  { wrongName: 'Blanche', level: 8, cool: false }
]

Maybe(data)
  .map(people => people.filter(person => person.cool))
  .chain(head)
  .chain(get(['name']))
  .map(name => name.toUpperCase())
  .cata({
    Just: data => console.log(data), // JASON
    Nothing: () => console.log('No data available')
  })
Collapse
 
yurakostin profile image
Yuri Kostin

It seems to looks better with Ramda, isn't it:

const data = [
  { wrongName: 'Jason', level: 7, cool: true },
  { wrongName: 'Blanche', level: 8, cool: false }
];

Maybe(data)
  .map(filter(propEq('cool', true)))
  .map(head)
  .map(prop('name'))
  .map(toUpper)
  .cata({
    Just: console.log
    Nothing: () => console.log('No data available')
  })

PS: thanks a lot for the article

Thread Thread
 
rametta profile image
Jason

This isn't exactly the same because Ramdas prop() does not return a Maybe, so if that prop did not exist then ramda would return an undefined, which will cause problems down the line. Same with head()

Thread Thread
 
yurakostin profile image
Yuri Kostin

You are totally right. Sorry for my mistake.