-
-
Notifications
You must be signed in to change notification settings - Fork 511
/
Copy pathfp-ts-to-the-max-I.ts
95 lines (83 loc) · 2.17 KB
/
fp-ts-to-the-max-I.ts
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import { createInterface } from 'readline'
import { log } from '../src/Console'
import { flow, pipe } from '../src/function'
import * as O from '../src/Option'
import { randomInt } from '../src/Random'
import * as T from '../src/Task'
//
// helpers
//
// read from standard input
const getStrLn: T.Task<string> = () =>
new Promise((resolve) => {
const rl = createInterface({
input: process.stdin,
output: process.stdout
})
rl.question('> ', (answer) => {
rl.close()
resolve(answer)
})
})
// write to standard output
const putStrLn = flow(log, T.fromIO)
// ask something and get the answer
function ask(question: string): T.Task<string> {
return pipe(
putStrLn(question),
T.flatMap(() => getStrLn)
)
}
// get a random int between 1 and 5
const random = T.fromIO(randomInt(1, 5))
// parse a string to an integer
function parse(s: string): O.Option<number> {
const i = +s
return isNaN(i) || i % 1 !== 0 ? O.none : O.some(i)
}
//
// game
//
function shouldContinue(name: string): T.Task<boolean> {
return pipe(
ask(`Do you want to continue, ${name} (y/n)?`),
T.flatMap((answer) => {
switch (answer.toLowerCase()) {
case 'y':
return T.of(true)
case 'n':
return T.of(false)
default:
return shouldContinue(name)
}
})
)
}
function gameLoop(name: string): T.Task<void> {
return pipe(
T.Do,
T.apS('secret', random),
T.apS('guess', ask(`Dear ${name}, please guess a number from 1 to 5`)),
T.flatMap(({ secret, guess }) =>
pipe(
parse(guess),
O.fold(
() => putStrLn('You did not enter an integer!'),
(x) =>
x === secret
? putStrLn(`You guessed right, ${name}!`)
: putStrLn(`You guessed wrong, ${name}! The number was: ${secret}`)
)
)
),
T.flatMap(() => shouldContinue(name)),
T.flatMap((b) => (b ? gameLoop(name) : T.of(undefined)))
)
}
const main: T.Task<void> = pipe(
ask('What is your name?'),
T.tap((name) => putStrLn(`Hello, ${name} welcome to the game!`)),
T.flatMap(gameLoop)
)
// tslint:disable-next-line: no-floating-promises
main()