Skip to content

Instantly share code, notes, and snippets.

@DominikStyp
Last active October 15, 2023 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DominikStyp/46e5530531ac4bb6efe10325a6b0158c to your computer and use it in GitHub Desktop.
Save DominikStyp/46e5530531ac4bb6efe10325a6b0158c to your computer and use it in GitHub Desktop.
JavaScript monad example

Paste this to the Chrome console and run and check the ret value

class Maybe {
constructor(v){
this.value = v;
};
bind(func) {
return new Maybe(func(this.value));
}
getValue() {
return this.value;
}
}
let arr = [1,2,3,4,5,6,7,8,9,0]
let maybe = new Maybe(arr);
let ret = maybe
.bind((arr) => arr.filter((v) => v > 1) )
.bind((arr) => arr.filter((v) => v < 8) )
.getValue()
return ret; // 2,3,4,5,6,7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment