-
Notifications
You must be signed in to change notification settings - Fork 3
/
fp.js
407 lines (337 loc) · 8.85 KB
/
fp.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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
const _ = '@@placeholder';
// curry :: ((a, b) -> c) -> a -> b -> c
const curry = (f, arr = []) => {
return (...args) => {
let j = 0;
// 跳过占位符
for (let i = 0; i < arr.length; i++) {
if (arr[i] === _) {
arr[i] = args[j++];
}
}
const combined = j < args.length ? [...arr, ...args.slice(j)] : [...arr];
const validArgs = combined.filter(arg => arg !== _);
return validArgs.length >= f.length ? f(...combined) : curry(f, combined);
};
};
// partial :: ((a, b) -> c) -> b -> c
const partial = (...args) => {
const func = args.shift();
return (...a) => {
const len = args.length;
let j = 0;
for (let i = 0; i < len; i++) {
if (args[i] === _) {
args[i] = a[j++];
}
}
if (j < a.length) {
args = [...args, ...a];
}
return func(...args);
}
}
// compose:: (Function f, Function g) -> Function z
const compose = (...funcs) => x => funcs.reduceRight((input, func) => func(input), x);
// property :: String -> a -> b
const property = curry((prop, obj) => obj[prop]);
// identity :: a->a
const identity = obj => obj;
// map :: (a->b) -> [a] -> [b]
const map = curry((fn, f) => f.map(fn));
// reduce :: (b->a->b) -> b -> [a] -> b
const reduce = curry((accumulator, initVal, f) => f.reduce(accumulator, initVal));
// lift :: AP ap => (a -> b) -> ap a -> [ap b] -> ap c
const lift = curry((f, functor1, ...args) => args.reduce(function (pre, next) {
return pre.ap(next);
}, functor1.map(f)));
// filter :: (a->Bool) -> [a] -> [a]
const filter = curry((fn, f) => f.filter(fn));
// last :: [a] -> b
const last = array => array[array.length - 1];
// head :: [a] -> b
const head = array => array[0];
// split :: Regexp -> String -> [a]
const split = curry((regex, s) => s.split(regex));
// match :: Regexp -> String -> [a]
const match = curry((regex, s) => s.match(regex));
// nth :: Number -> [a] -> b
const nth = curry((nth, arr) => nth < 0 ? arr[arr.length + nth] : arr[nth]);
// trace -> String -> a -> a
const trace = curry((tag, x) => {
console.log(tag, x);
return x;
});
// log -> String -> String -> a -> a
const log = curry((level, tag, x) => {
switch (level) {
case 'error':
console.error(tag, x);
break;
case 'debug':
default:
console.log(tag, x);
break;
}
return x;
});
//////////////// Functors //////////////////////
// Identity
const Identity = function (x) {
this.__value = x;
};
Identity.of = function (x) { return new Identity(x); };
Identity.prototype.map = function (f) {
return Identity.of(f(this.__value));
};
Identity.prototype.inspect = function () {
return `Identity(${inspect(this.__value)})`;
};
Identity.prototype.toString = function () {
return `Identity(${this.__value})`;
}
// Maybe
const Maybe = function (v) {
this.__value = v;
}
Maybe.of = function (v) {
return new Maybe(v);
}
Maybe.prototype.isNothing = function () {
return this.__value === null || this.value === undefined;
}
Maybe.prototype.map = function (f) {
return this.isNothing() ? Maybe.of(null) : Maybe.of(f(this.__value));
}
Maybe.prototype.join = function () {
return this.isNothing() ? Maybe.of(null) : this.__value;
}
Maybe.prototype.chain = function (f) {
return this.map(f).join();
}
Maybe.prototype.ap = function (other) {
return this.isNothing() ? Maybe.of(null) : other.map(this.__value);
}
Maybe.prototype.inspect = function () {
return `Maybe(${inspect(this.__value)})`;
}
Maybe.prototype.toString = function () {
return `Maybe(${this.__value})`;
}
// Left
const Left = function (v) {
this.__value = v;
}
Left.of = function (v) {
return new Left(v);
}
Left.prototype.map = function (f) {
// Left functor 会短路之后的一切操作
return this;
}
Left.prototype.join = function () {
return this;
}
Left.prototype.chain = function (f) {
return this;
}
Left.prototype.ap = function (other) {
return this;
}
Left.prototype.inspect = function () {
return `Left(${inspect(this.__value)})`;
}
Left.prototype.toString = function () {
return `Left(${this.__value})`;
}
// Right
const Right = function (v) {
this.__value = v;
}
Right.of = function (v) {
return new Right(v);
}
Right.prototype.map = function (f) {
return Right.of(f(this.__value));
}
Right.prototype.join = function () {
return this.__value;
}
Right.prototype.chain = function (f) {
return this.map(f).join();
}
Right.prototype.ap = function (other) {
return other.map(this.__value);
}
Right.prototype.inspect = function () {
return `Right(${inspect(this.__value)})`;
}
Right.prototype.toString = function () {
return `Right(${this.__value})`;
}
// Either
Either = function () {}
Either.of = function (v) {
return Right.of(v);
}
// IO
const IO = function (f) {
this.unsafePerformIO = f;
}
IO.prototype.of = function (v) {
return new IO(function () {
return v;
});
}
IO.prototype.map = function (f) {
return new IO(compose(f, this.unsafePerformIO));
}
IO.prototype.join = function () {
return this.unsafePerformIO();
}
IO.prototype.chain = function (f) {
return this.map(f).join();
}
IO.prototype.ap = function (other) {
return other.map(this.unsafePerformIO)
}
IO.prototype.inspect = function () {
return `IO(${inspect(this.unsafePerformIO)})`;
}
IO.prototype.toString = function () {
return `IO(${this.unsafePerformIO})`;
}
const Task = function (f, tasks, cb) {
this.fork = f;
this.tasks = tasks;
this.cb = cb;
}
Task.of = function (f) {
return new Task(f);
}
Task.prototype.map = function (f) {
let self = this;
return new Task((reject, resolve) =>
self.fork(error => reject(error), data => resolve(f(data)))
);
}
Task.prototype.chain = function (f) {
let self = this;
return new Task((reject, resolve) =>
self.fork(error => reject(error), data => f(data).fork(reject, resolve))
);
}
Task.prototype.ap2 = function (task) {
const cb = this.cb === void 0 ? this.fork : this.cb;
const tasks = this.tasks === void 0 ? [task] : this.tasks.map(identity).concat([task]);
const results = new Array(tasks.length);
let completed = tasks.length;
let failed = false
return new Task((reject, resolve) =>
tasks.forEach((task, index) => {
if (!failed) {
task.fork(error => {
failed = true;
reject(error);
}, data => {
results[index] = data;
if (--completed === 0) {
resolve(cb.apply(null, results));
}
})
}
}), tasks, cb);
}
Task.prototype.ap = function (that) {
let forkThis = this.fork;
let forkThat = that.fork;
return new Task((reject, resolve) => {
let func, funcLoaded = false;
let val, valLoaded = false;
let rejected = false;
const guardResolve = (setter) => (x) => {
if (rejected) {
return;
}
setter(x);
// 保证异步处理都结束并成功后再执行回调
if (funcLoaded && valLoaded) {
return resolve(func(val));
} else {
return x;
}
}
const guardReject = (x) => {
if (!rejected) {
rejected = true;
return reject(x);
}
}
let thisState = forkThis(guardReject, guardResolve((x) => {
funcLoaded = true;
func = x;
}));
let thatState = forkThat(guardReject, guardResolve((x) => {
valLoaded = true;
val = x;
}))
return [thisState, thatState];
});
}
Task.all = function (tasks) {
const results = new Array(tasks.length);
let completed = tasks.length;
return new Task((reject, resolve) =>
tasks.forEach((task, index) =>
task.fork(error => reject(error), data => {
results[index] = data;
if (--completed === 0) {
resolve(results);
}
})
)
);
}
///// Functor Helper //////////////
const fmap = curry((f, m) => m.map(f));
const fchain = curry((f, m) => m.chain(f));
const feither = curry((f, g, e) => {
switch (e.constructor) {
case Left:
return f(e.__value);
case Right:
return g(e.__value);
}
});
inspect = function (x) {
return (x && x.inspect) ? x.inspect() : x;
};
module.exports = {
_,
curry,
partial,
compose,
property,
identity,
map,
lift,
reduce,
filter,
last,
head,
split,
match,
nth,
trace,
log,
Identity,
fmap,
fchain,
feither,
Maybe,
Left,
Right,
Either,
IO,
Task
};