Can anyone solve the challenge below (i.e. mapping over dataBad
) using monads or similar FP implementation (NB caveat, can this be done in a way that would be familiar to Javascript developers)?
const dataGood = [ { a: { b: 1 } }, { a: { b: 2 } }, { a: { b: 3 } } ]
const dataBad = [ { a: { b: 1 } }, { a: { b: 2 } }, { b: { c: 3 } } ]
// returns array
return dataGood
.map(obj => obj.a) // [ { b: 1 }, { b: 2 }, { b: 3 } ]
.map(obj => obj.b + 1) // [ 2, 3, 4 ]
// breaks application
return dataBad
.map(obj => obj.a) // [ { b: 1 }, { b: 2 }, undefined ]
.map(obj => obj.b + 1) // TypeError: Cannot read property 'b' of undefined
POSSIBLE ANSWER: If Promise
's are essentially monads, then wouldn't this be the most simple / javascript-esque monad implementation?
const Maybe = val => new Promise(resolve => resolve(val))
const dataGood = [ { a: { b: 1 } }, { a: { b: 2 } }, { a: { b: 3 } } ]
const dataBad = [ { a: { b: 1 } }, { a: { b: 2 } }, { b: { c: 3 } } ]
// returns null
return await Maybe(dataBad)
.then(val => val.map(obj => obj.a) ) // [ { b: 1 }, { b: 2 }, undefined ]
.then(val => val.map(obj => obj.b + 1) ) // TypeError: Cannot read property 'b' of undefined
.catch(() => null)