-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtransducers.js
482 lines (419 loc) · 10.6 KB
/
transducers.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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
if (typeof(Symbol) === 'undefined') {
var Symbol = name => `${name}@transducer`
Symbol.iterator = '@@iterator'
}
const compose = (f, g) => (...args) => f(g(...args));
const prototype = Object.prototype
const isArray = Array.isArray ||
x => prototype.toString.call(x) === '[object Array]'
const isIterator = x =>
x && (x[Symbol.iterator] || typeof(x.next) === 'function')
const isRegExp = x =>
prototype.toString.call(x) === '[object RegExp]'
export class Reduced {
constructor(value) {
this.value = value
this[Reduced.symbol] = true
}
}
Reduced.symbol = Symbol('reduced')
export const isReduced = x =>
x instanceof Reduced ||
(x && x[Reduced.symbol])
export class Reducer {
constructor({empty, step, result}) {
this.empty = empty || this.empty
this.step = step || this.step
this.result = result || this.result
}
empty() {
throw TypeError('Reducer must implement .empty method')
}
step(result, input) {
throw TypeError('Reducer must implement .step method')
}
result(value) {
throw TypeError('Reducer must implement .result method')
}
}
export class Transducer extends Reducer {
constructor(reducer, ...params) {
this.reducer = reducer
this.setup(...params)
}
setup() {
}
empty() {
return this.reducer.empty()
}
step(state, input) {
this.advance(state, input)
}
advance(state, input) {
return this.reducer.step(state, input)
}
result(state) {
return this.reducer.result(state)
}
}
export const Transform = (TransducerType, ...params) => {
const transform = source => {
if (source instanceof Reducer) {
return new TransducerType(source, ...params)
} else if (source && source[Transform.symbol]) {
return compose(source, transform)
} else {
return transduce(source, transform, reducer(source))
}
}
transform[Transform.symbol] = true
transform.Transducer = TransducerType
transform.params = params
return transform
}
Transform.symbol = Symbol('transform')
export const Transformer = TransducerType => (...params) =>
Transform(TransducerType, ...params)
class Map extends Transducer {
setup(f) {
this.f = f
}
step(state, input) {
return this.advance(state, this.f(input))
}
}
export const map = Transformer(Map)
class Filter extends Transducer {
setup(p) {
this.p = p
}
step(state, input) {
if (this.p(input)) {
return this.advance(state, input)
}
return state
}
}
export const filter = Transformer(Filter)
export const remove = p => filter(x => !p(x))
class DropRepeats extends Transducer {
step(state, input) {
if (input !== this.last) {
this.last = input
return this.advance(state, input)
}
return state
}
}
export const dropRepeats = Transform(DropRepeats)
class TakeWhile extends Transducer {
setup(p) {
this.p = p
}
step(state, input) {
if (this.p(input)) {
return this.advance(state, input)
}
return new Reduced(state)
}
}
export const takeWhile = Transformer(TakeWhile)
class Take extends Transducer {
setup(n) {
this.n = n
}
step(state, input) {
if (this.n > 0) {
this.n = this.n - 1
state = this.advance(state, input)
if (this.n === 0 && !isReduced(state)) {
state = new Reduced(state)
}
}
return state
}
}
export const take = Transformer(Take)
class Drop extends Transducer {
setup(n) {
this.n = n
}
step(state, input) {
this.n = this.n - 1;
return this.n >= 0 ? state : this.advance(state, input)
}
}
export const drop = Transformer(Drop)
class DropWhile extends Transducer {
setup(p) {
this.p = p
this.dropping = true
}
step(state, input) {
this.dropping = this.dropping && this.p(input)
return this.dropping ? state : this.advance(state, input)
}
}
export const dropWhile = Transformer(DropWhile)
class Partition extends Transducer {
setup(n) {
this.n = n
this.i = 0
this.part = new Array(n)
}
result(state) {
if (this.i > 0) {
state = this.advance(state, this.part.slice(0, this.i))
state = isReduced(state) ? state.value : state
}
return super.result(state)
}
step(state, input) {
this.part[this.i] = input
this.i = this.i + 1
if (this.i == this.n) {
this.i = 0
return this.advance(state, this.part.slice(0))
}
return state
}
}
export const partition = Transformer(Partition)
class Forwarder extends Transducer {
step(state, input) {
const result = this.advance(state, input)
return isReduced(result) ? result.value : result
}
}
class Cat extends Transducer {
setup() {
this.forwarder = new Forwarder(this.reducer)
}
step(state, input) {
return reduce(input, this.forwarder, state)
}
}
export const cat = Transform(Cat)
export const mapcat = f => compose(cat, map(f))
export const transduce = (source, transformer, reducer, initial) => {
if (!reducer) throw TypeError('transduce must be passed a reducer')
const transducer = transformer(reducer)
const result = reduce(source, transducer,
initial !== void(0) ? initial : transducer.empty())
return transducer.result(result)
}
const Types = {
Array: {},
Iterator: {},
String: {},
Number: {},
Boolean: {},
Null: {},
Void: {},
RegExp: {},
Symbol: {},
Default: {}
}
const methodsOf = target =>
target === null ? Types.Null :
target === void(0) ? Types.Void :
isArray(target) ? Types.Array :
isIterator(target) ? Types.Iterator :
typeof(target) === 'object' ? target :
typeof(target) === 'function' ? Types.Function :
typeof(target) === 'string' ? Types.String :
typeof(target) === 'number' ? Types.Number :
typeof(target) === 'boolean' ? Types.Boolean :
isRegExp(target) ? Types.RegExp :
typeof(target) === 'symbol' ? Types.Symbol :
Types.Default;
export const reduce = (source, transducer, initial) =>
methodsOf(source)[reduce.symbol](source, transducer, initial);
reduce.symbol = Symbol('reduce')
Types.Array[reduce.symbol] = (array, transducer, state) => {
let index = -1
const count = array.length
while(++index < count) {
state = transducer.step(state, array[index])
if (isReduced(state)) {
state = state.value
break
}
}
return state
}
Types.String[reduce.symbol] = Types.Array[reduce.symbol]
Types.Iterator[reduce.symbol] = (iterator, transducer, state) => {
// If iterator without custom `transcieve` operation is being
// transduced we don't need to walk the iterator now we can transform
// it lazily there for we create `Iteratornsformation` and pass
// it source iterator and a transciever so it could perform these steps
// lazily.
if (state === IteratorLazyTransformation.Empty) {
return new IteratorLazyTransformation(iterator, transducer)
}
// Otherwise we forward individual values.
let {done, value} = iterator.next()
while(!done) {
state = transducer.step(state, value)
if (isReduced(state)) {
state = state.value
break;
}
({done, value}) = iterator.next()
}
return state
}
const reduceSingular = (unit, reducer, state) => {
const result = reducer.step(state, unit)
return isReduced(result) ? result.value : result
}
Types.Null[reduce.symbol] = reduceSingular
Types.Void[reduce.symbol] = reduceSingular
Types.Number[reduce.symbol] = reduceSingular
export const reducer = source => methodsOf(source)[reducer.symbol]
reducer.symbol = Symbol('reducer')
Types.Array[reducer.symbol] = new Reducer({
empty() {
return []
},
result(array) {
return array
},
step(array, input) {
array.push(input)
return array
}
})
Types.Number[reducer.symbol] = new Reducer({
empty() {
return 0
},
result(number) {
return number
},
step(number, input) {
return isArray(input) ? input.reduce(this.step, number) :
number + input
}
})
Types.String[reducer.symbol] = new Reducer({
empty() {
return ""
},
result(string) {
return string
},
step(string, input) {
return isArray(input) ? string.concat(...input) :
string + input
}
})
Types.Null[reducer.symbol] = new Reducer({
empty() {
return null
},
result(value) {
return value
},
step(_, input) {
return null
}
})
Types.Void[reducer.symbol] = new Reducer({
empty() {
return void(0)
},
result(value) {
return value
},
step(_, input) {
return void(0)
}
})
const nil = {}
Types.Iterator[reducer.symbol] = new Reducer({
empty() {
return IteratorLazyTransformation.Empty
},
step(target, value) {
target.buffer.push(value)
return target
},
result(target) {
return target
}
})
class IteratorLazyTransformation {
constructor(source, transducer) {
this.source = source
this.transducer = transducer
this.buffer = []
this.isDrained = false
this.done = false
}
[Symbol.iterator]() {
return this
}
next() {
// Pull from the source until something ends up in a buffer
// or until source is drained. Note that transducer maybe
// filtering so it may take multiple steps until something
// is being pushed to buffer. It also maybe that transducer
// is accumulating until result is called.
while (this.buffer.length === 0 && !this.isDrained) {
const {done, value} = this.source.next()
if (done) {
this.transducer.result(this)
this.isDrained = done
} else {
const result = this.transducer.step(this, value)
this.isDrained = isReduced(result)
}
}
// At this poin we either managed to get something pushed
// to a buffer or source was exhausted or both. If something
// was pushed to a buffer we do not end until buffer is empty,
// so we start with that.
if (this.buffer.length > 0) {
this.value = this.buffer.shift()
} else {
this.done = this.isDrained
}
return this
}
}
IteratorLazyTransformation.Empty = new String("IteratorLazyTransformation.Empty")
IteratorLazyTransformation.Nil = new String("IteratorLazyTransformation.Nil")
/*
class ChannelInputReducer {
empty() {
return new Channel()
}
result(channel) {
return channel.input
}
step(channel, chunk) {
return channel.output.put(chunk)
}
}
const reduceChannelInput = (source, transducer, channel) => {
spawn(function*() {
let chunk = void(0)
let state = void(0)
while (chunk = yield channel.input.take()) {
state = yield transducer.recieve(channel, chunk);
if (isReduced(state)) {
state = state.value
break;
}
}
channel.output.close()
return state
})
return transducer.result(channel)
}
*/
const inc = x => x + 1
const isEven = x => !(x % 2)
const upperCase = string => string.toUpperCase()