@rgeraldporter/

Maybe Monad Example

Nodejs

No description

fork
loading
Files
  • index.js
  • Maybe.js
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const { Maybe } = require('./Maybe');

const fahrenheitToCelsius = a => (a - 32) * 0.5556;

const reading1 = 15;
const reading2 = null;

const temp1C = Maybe.of(reading1)
					.map(fahrenheitToCelsius);
					
console.log(temp1C.inspect());
// > Just(-9.4444)
					
const temp2C = Maybe.of(reading2)
					.map(fahrenheitToCelsius);

console.log(temp2C.inspect());
// > Nothing()

const display = a => {
	console.log(a);
	return a;
};

Maybe.of(reading1)
	.map(fahrenheitToCelsius)
	.fork(
		_ => display('ERR!'),
		t => display(`${t}°C`) // will read `-9.4452°C`
	);
					
Maybe.of(reading2)
	.map(fahrenheitToCelsius)
	.fork(
		_ => display('ERR!'), // will read `ERR!`
		t => display(`${t}°C`)
	);

const temp3C = Maybe.of(reading1)
	.map(fahrenheitToCelsius)
	.fork(
		_ => display('ERR!'),
		t => display(`${t}°C`)
	);
	
console.log(temp3C)
// > "-9.4452°C"
node v10.16.0