Skip to content

Instantly share code, notes, and snippets.

@sudaraka
Created September 4, 2016 07:41
Show Gist options
  • Save sudaraka/7fffd0223dceac544f48cb73067521b5 to your computer and use it in GitHub Desktop.
Save sudaraka/7fffd0223dceac544f48cb73067521b5 to your computer and use it in GitHub Desktop.
const
R = require('ramda'),
fs = require('fs')
// == Maybe ====================================================================
const
Maybe = function(x) {
this.__value = x
}
Maybe.of = function(x) {
return new Maybe(x)
}
Maybe.prototype.isNothing = function() {
return null === this.__value || 'undefined' === typeof this.__value
}
Maybe.prototype.map = function(f) {
return this.isNothing() ? Maybe.of(null) : Maybe.of(f(this.__value))
}
Maybe.prototype.join = function() {
return this.isNothing() ? Maybe.of(null) : this.__value
}
Maybe.prototype.chain = function(f) {
return this.map(f).join()
}
// == Maybe ====================================================================
// == IO =======================================================================
const
IO = function(f) {
this.__value = f
}
IO.of = function(x) {
return new IO(function() {
return x
})
}
IO.prototype.map = function(f) {
return new IO(R.compose(f, this.__value))
}
IO.prototype.join = function() {
return this.__value()
}
IO.prototype.chain = function(f) {
return this.map(f).join()
}
// == IO =======================================================================
const
readFile = function(filename) {
return new IO(function() {
return fs.readFileSync(filename, 'utf-8')
})
},
print = function(x) {
return new IO(function() {
console.log('Printing:', x)
return x
})
},
safeProp = R.curry(function(x, obj) {
return new Maybe(obj[x])
}),
safeHead = safeProp(0),
join = m => m.join(),
// chain = R.curry(function(f, m) {
// return m.chain(f)
// })
cat = R.compose(
join,
R.chain(print),
readFile
),
firstAddressStreet = R.compose(
R.chain(safeProp('street')),
R.chain(safeHead),
safeProp('addresses')
)
console.log('== IO ==================================')
console.log(
cat('package.json')
)
console.log('\n== Maybe (basic) =======================')
console.log(
Maybe.of('Malkovich Malkovich').map(R.match(/a/ig))
)
console.log(
Maybe.of(null).map(R.match(/a/ig))
)
console.log(
Maybe.of({ 'name': 'Pissa' }).map(R.prop('age')).map(R.add(10))
)
console.log(
Maybe.of({ 'name': 'Suda', 'age': 36 }).map(R.prop('age')).map(R.add(10))
)
console.log('\n== Maybe (nested) ======================')
console.log(
firstAddressStreet({addresses: [{street: {name: 'Mulburry', number: 8402}, postcode: "WC2N" }]})
)
console.log('\n========================================')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment