Last active
November 24, 2017 19:26
-
-
Save zerobias/84d3452ab626c8cc84c8dba0ec9e5f6e to your computer and use it in GitHub Desktop.
Minimal maybe example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Example with no .value in instances. Its can be much slower, | |
* but if you prefer pureness, that is your choice | |
*/ | |
export const just = data => new Just( data ) | |
export const of = just | |
export const nothing = () => new Nothing | |
const allocation = new WeakMap | |
class Just { | |
constructor(value) { allocation.set(this, value) } | |
map(fn) { | |
return new Just(fn( allocation.get(this) )) | |
} | |
chain( fn ) { | |
return fn( allocation.get(this) ) | |
} | |
filter( cond ) { | |
const value = allocation.get(this) | |
return cond( value ) | |
? new Just( value ) | |
: new Nothing | |
} | |
fold( fnN, fnJ ) { | |
return fnJ( allocation.get(this) ) | |
} | |
} | |
class Nothing { | |
map(fn) { | |
return this | |
} | |
chain( fn ) { | |
return this | |
} | |
filter( cond ) { | |
return this | |
} | |
fold( fnN, fnJ ) { | |
return fnN() | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const just = data => new Just( data ) | |
export const of = just | |
export const nothing = () => new Nothing | |
// Optimisation: you can create and use same Nothing value | |
// and became even faster | |
class Just { | |
constructor(value) { this.value = value } | |
map(fn) { | |
return new Just(fn( this.value )) | |
} | |
chain( fn ) { | |
return fn( this.value ) | |
} | |
filter( cond ) { | |
return cond( this.value ) | |
? new Just( this.value ) | |
: new Nothing | |
} | |
fold( fnN, fnJ ) { | |
return fnJ( this.value ) | |
} | |
} | |
class Nothing { | |
map(fn) { | |
return this | |
} | |
chain( fn ) { | |
return this | |
} | |
filter( cond ) { | |
return this | |
} | |
fold( fnN, fnJ ) { | |
return fnN() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment