-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path7-either.js
More file actions
115 lines (87 loc) · 2.56 KB
/
7-either.js
File metadata and controls
115 lines (87 loc) · 2.56 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
'use strict';
//була зроблена функція для обчислення податку з доходу
//для зчитування введення з клавіатури
const readline = require('node:readline');
//податок (24%)
const taxRate = 0.24;
class Either {
#left = null;
#right = null;
constructor({ left = null, right = null }) {
this.#left = left;
this.#right = right;
}
static left(value) {
return new Either({ left: value, right: null });
}
static right(value) {
return new Either({ left: null, right: value });
}
get left() {
return this.#left;
}
get right() {
return this.#right;
}
isLeft() {
return this.#left !== null;
}
isRight() {
return this.#right !== null;
}
map(fn) {
if (this.#right === null) return this;
return Either.right(fn(this.#right));
}
match(leftFn, rightFn) {
const isRight = this.#right !== null;
return isRight ? rightFn(this.#right) : leftFn(this.#left);
}
}
// Usage
/*
const success = Either.right(42);
const failure = Either.left(500);
const doubled = success.map((x) => x * 2);
console.log({ doubled: doubled.right });
const result = failure.match(
(error) => `Failure: ${error}`,
(value) => `Success: ${value}`,
);
console.log({ result });
*/
//функція для обчислення податку з доходу
function calculateTax(income) {
if (isNaN(income) || income <= 0) {
// Якщо ні то помилка (left)
return Either.left('Invalid income amount');
}
const tax = income * taxRate;
//якщо немає помилки (right)
return Either.right({ tax, rate: taxRate });
}
//зчитування введення користувача
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
//логіка взаємодії з користувачем
rl.question('Введіть ваш дохід: ', (input) => {
const income = Number(input);
//виклик функції розрахунку податку
calculateTax(income)
//знаки після коми при успіху (right)
.map(({ tax, rate }) => ({
tax: tax.toFixed(2),
rate: (rate * 100).toFixed(0) + '%'
}))
//обробка результату
.match(
(err) => console.log('Помилка:', err),
({ tax, rate }) => {
console.log('Податок становить:', tax, 'при ставці', rate);
console.log('[LOG] Розрахунок виконано успішно.');
}
);
rl.close();
});