-
Notifications
You must be signed in to change notification settings - Fork 15
/
map.js
535 lines (522 loc) · 14.6 KB
/
map.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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
const isPromise = require('./_internal/isPromise')
const MappingIterator = require('./_internal/MappingIterator')
const MappingAsyncIterator = require('./_internal/MappingAsyncIterator')
const __ = require('./_internal/placeholder')
const curry2 = require('./_internal/curry2')
const curry3 = require('./_internal/curry3')
const isArray = require('./_internal/isArray')
const isObject = require('./_internal/isObject')
const arrayMap = require('./_internal/arrayMap')
const stringMap = require('./_internal/stringMap')
const setMap = require('./_internal/setMap')
const mapMap = require('./_internal/mapMap')
const objectMap = require('./_internal/objectMap')
const arrayMapSeries = require('./_internal/arrayMapSeries')
const stringMapSeries = require('./_internal/stringMapSeries')
const objectMapSeries = require('./_internal/objectMapSeries')
const setMapSeries = require('./_internal/setMapSeries')
const mapMapSeries = require('./_internal/mapMapSeries')
const arrayMapPool = require('./_internal/arrayMapPool')
const stringMapPool = require('./_internal/stringMapPool')
const setMapPool = require('./_internal/setMapPool')
const mapMapPool = require('./_internal/mapMapPool')
const objectMapPool = require('./_internal/objectMapPool')
const objectMapEntries = require('./_internal/objectMapEntries')
const mapMapEntries = require('./_internal/mapMapEntries')
const symbolIterator = require('./_internal/symbolIterator')
const symbolAsyncIterator = require('./_internal/symbolAsyncIterator')
/**
* @name _map
*
* @synopsis
* ```coffeescript [specscript]
* _map(
* array Array,
* arrayMapper (value any, index number, array Array)=>Promise|any
* ) -> mappedArray Promise|Array
*
* _map(
* object Object,
* objectMapper (value any, key string, object Object)=>Promise|any
* ) -> mappedObject Promise|Array
*
* _map(
* set Set,
* setMapper (value any, value, set Set)=>Promise|any
* ) -> mappedSet Promise|Set
*
* _map(
* originalMap Map,
* mapMapper (value any, key any, originalMap Map)=>Promise|any
* ) -> mappedMap Promise|Map
* ```
*/
const _map = function (value, f) {
if (isArray(value)) {
return arrayMap(value, f)
}
if (value == null) {
return value
}
if (typeof value.then == 'function') {
return value.then(f)
}
if (typeof value.map == 'function') {
return value.map(f)
}
if (typeof value == 'string' || value.constructor == String) {
return stringMap(value, f)
}
if (value.constructor == Set) {
return setMap(value, f)
}
if (value.constructor == Map) {
return mapMap(value, f)
}
if (typeof value[symbolIterator] == 'function') {
return MappingIterator(value[symbolIterator](), f)
}
if (typeof value[symbolAsyncIterator] == 'function') {
return MappingAsyncIterator(value[symbolAsyncIterator](), f)
}
if (value.constructor == Object) {
return objectMap(value, f)
}
return f(value)
}
/**
* @name map
*
* @synopsis
* ```coffeescript [specscript]
* type Mappable = Array|Object|Set|Map|Iterator|AsyncIterator
*
* type Mapper = (
* value any,
* indexOrKey number|string|any,
* collection Mappable
* )=>(resultItem Promise|any)
*
* map(collection Promise|Mappable, f Mapper) -> result Promise|Mappable
* map(f Mapper)(collection Mappable) -> result Promise|Mappable
* ```
*
* @description
* Applies a synchronous or asynchronous mapper function `f` concurrently to each item of a collection, returning the results in a new collection of the same type. If order is implied by the collection, it is maintained in the result. `map` accepts the following collections:
*
* * `Array`
* * `Object`
* * `Set`
* * `Map`
* * `Iterator`/`Generator`
* * `AsyncIterator`/`AsyncGenerator`
*
* With arrays (type `Array`), `map` applies the mapper function `f` to each item of the array, returning the transformed results in a new array ordered the same as the original array.
*
* ```javascript [playground]
* const square = number => number ** 2
*
* const array = [1, 2, 3, 4, 5]
*
* console.log(
* map(array, square)
* ) // [1, 4, 9, 16, 25]
*
* console.log(
* map(square)(array)
* ) // [1, 4, 9, 16, 25]
* ```
*
* With objects (type `Object`), `map` applies the mapper function `f` to each value of the object, returning the transformed results as values in a new object ordered by the keys of the original object
*
* ```javascript [playground]
* const square = number => number ** 2
*
* const obj = { a: 1, b: 2, c: 3, d: 4, e: 5 }
*
* console.log(
* map(square)(obj)
* ) // { a: 1, b: 4, c: 9, d: 16, e: 25 }
*
* console.log(
* map(obj, square)
* ) // { a: 1, b: 4, c: 9, d: 16, e: 25 }
* ```
*
* With sets (type `Set`), `map` applies the mapper function `f` to each value of the set, returning the transformed results unordered in a new set.
*
* ```javascript [playground]
* const square = number => number ** 2
*
* const set = new Set([1, 2, 3, 4, 5])
*
* console.log(
* map(set, square)
* ) // [1, 4, 9, 16, 25]
*
* console.log(
* map(square)(set)
* ) // [1, 4, 9, 16, 25]
* ```
*
* With maps (type `Map`), `map` applies the mapper function `f` to each value of the map, returning the results at the same keys in a new map. The entries of the resulting map are in the same order as those of the original map
*
* ```javascript [playground]
* const square = number => number ** 2
*
* const m = new Map([['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]])
*
* console.log(
* map(square)(m)
* ) // Map { 'a' => 1, 'b' => 4, 'c' => 9, 'd' => 16, 'e' => 25 }
*
* console.log(
* map(m, square)
* ) // Map { 'a' => 1, 'b' => 4, 'c' => 9, 'd' => 16, 'e' => 25 }
* ```
*
* With iterators (type `Iterator`) or generators (type `Generator`), `map` applies the mapper function `f` lazily to each value of the iterator/generator, creating a new iterator with transformed iterations.
*
* ```javascript [playground]
* const capitalize = string => string.toUpperCase()
*
* const abcGeneratorFunc = function* () {
* yield 'a'; yield 'b'; yield 'c'
* }
*
* const abcGenerator = abcGeneratorFunc()
* const ABCGenerator = map(abcGeneratorFunc(), capitalize)
* const ABCGenerator2 = map(capitalize)(abcGeneratorFunc())
*
* console.log([...abcGenerator]) // ['a', 'b', 'c']
*
* console.log([...ABCGenerator]) // ['A', 'B', 'C']
*
* console.log([...ABCGenerator2]) // ['A', 'B', 'C']
* ```
*
* With asyncIterators (type `AsyncIterator`, or `AsyncGenerator`), `map` applies the mapper function `f` lazily to each value of the asyncIterator, creating a new asyncIterator with transformed iterations
*
* ```javascript [playground]
* const capitalize = string => string.toUpperCase()
*
* const abcAsyncGeneratorFunc = async function* () {
* yield 'a'; yield 'b'; yield 'c'
* }
*
* const abcAsyncGenerator = abcAsyncGeneratorFunc()
* const ABCGenerator = map(abcAsyncGeneratorFunc(), capitalize)
* const ABCGenerator2 = map(capitalize)(abcAsyncGeneratorFunc())
*
* ;(async function () {
* for await (const letter of abcAsyncGenerator) {
* console.log(letter)
* // a
* // b
* // c
* }
*
* for await (const letter of ABCGenerator) {
* console.log(letter)
* // A
* // B
* // C
* }
*
* for await (const letter of ABCGenerator2) {
* console.log(letter)
* // A
* // B
* // C
* }
* })()
* ```
*
* Any promises passed in argument position are resolved for their values before further execution. This only applies to the eager version of the API.
*
* ```javascript [playground]
* const asyncSquare = async n => n ** 2
*
* map(Promise.resolve([1, 2, 3, 4, 5]), asyncSquare).then(console.log)
* // [1, 4, 9, 16, 25]
* ```
*
* @execution concurrent
*
* @TODO streamMap
*/
const map = function (arg0, arg1) {
if (arg1 == null) {
return curry2(_map, __, arg0)
}
return isPromise(arg0)
? arg0.then(curry2(_map, __, arg1))
: _map(arg0, arg1)
}
// _mapEntries(value Object|Map, f function) -> Object|Map
const _mapEntries = (value, f) => {
if (value == null) {
throw new TypeError('value is not an Object or Map')
}
if (value.constructor == Object) {
return objectMapEntries(value, f)
}
if (value.constructor == Map) {
return mapMapEntries(value, f)
}
throw new TypeError('value is not an Object or Map')
}
/**
* @name map.entries
*
* @synopsis
* ```coffeescript [specscript]
* type EntriesMappable = Object|Map
*
* type Mapper = (
* value any,
* key string|any,
* collection EntriesMappable
* )=>(resultItem Promise|any)
*
* map.entries(value Promise|EntriesMappable, f Mapper)
* -> Promise|EntriesMappable
*
* map.entries(f Mapper)(value EntriesMappable)
* -> Promise|EntriesMappable
* ```
*
* @description
* `map` over the entries rather than the values of a collection. Accepts collections of type `Map` or `Object`.
*
* ```javascript [playground]
* const upperCaseKeysAndSquareValues =
* map.entries(([key, value]) => [key.toUpperCase(), value ** 2])
*
* console.log(upperCaseKeysAndSquareValues({ a: 1, b: 2, c: 3 }))
* // { A: 1, B: 4, C: 9 }
*
* console.log(upperCaseKeysAndSquareValues(new Map([['a', 1], ['b', 2], ['c', 3]])))
* // Map(3) { 'A' => 1, 'B' => 4, 'C' => 9 }
* ```
*
* Any promises passed in argument position are resolved for their values before further execution. This only applies to the eager version of the API.
*
* ```javascript [playground]
* const asyncSquareEntries = async ([k, v]) => [k, v ** 2]
*
* map.entries(
* Promise.resolve({ a: 1, b: 2, c: 3 }),
* asyncSquareEntries,
* ).then(console.log)
* // { a: 1, b: 4, c: 9 }
* ```
*
* @since v1.7.0
*/
map.entries = function mapEntries(arg0, arg1) {
if (arg1 == null) {
return curry2(_mapEntries, __, arg0)
}
return isPromise(arg0)
? arg0.then(curry2(_mapEntries, __, arg1))
: _mapEntries(arg0, arg1)
}
/**
* @name _mapSeries
*
* @synopsis
* ```coffeescript [specscript]
* type Mappable = Array|Object|Set|Map
*
* type Mapper = (
* value any,
* indexOrKey number|string|any,
* collection Mappable
* )=>(mappedItem Promise|any)
*
* _mapSeries(collection Mappable, f Mapper) -> result Promise|Mappable
* ```
*/
const _mapSeries = function (collection, f) {
if (isArray(collection)) {
return arrayMapSeries(collection, f)
}
if (collection == null) {
throw new TypeError(`invalid collection ${collection}`)
}
if (typeof collection == 'string' || collection.constructor == String) {
return stringMapSeries(collection, f)
}
if (collection.constructor == Set) {
return setMapSeries(collection, f)
}
if (collection.constructor == Map) {
return mapMapSeries(collection, f)
}
if (collection.constructor == Object) {
return objectMapSeries(collection, f)
}
throw new TypeError(`invalid collection ${collection}`)
}
/**
* @name map.series
*
* @synopsis
* ```coffeescript [specscript]
* type Mappable = Array|Object|Set|Map
*
* type Mapper = (
* value any,
* indexOrKey number|string|any,
* collection Mappable
* )=>(mappedItem Promise|any)
*
* map.series(collection Promise|Mappable, f Mapper) -> result Mappable
* map.series(f Mapper)(collection Mappable) -> result Mappable
* ```
*
* @description
* [map](/docs/map) with serial execution.
*
* ```javascript [playground]
* const delayedLog = number => new Promise(function (resolve) {
* setTimeout(function () {
* console.log(number)
* resolve()
* }, 1000)
* })
*
* console.log('start')
* map.series([1, 2, 3, 4, 5], delayedLog)
* ```
*
* Any promises passed in argument position are resolved for their values before further execution. This only applies to the eager version of the API.
*
* ```javascript [playground]
* const asyncSquare = async n => n ** 2
*
* map.series(Promise.resolve([1, 2, 3, 4, 5]), asyncSquare).then(console.log)
* // [1, 4, 9, 16, 25]
* ```
*
* @execution series
*/
map.series = function mapSeries(arg0, arg1) {
if (arg1 == null) {
return curry2(_mapSeries, __, arg0)
}
return isPromise(arg0)
? arg0.then(curry2(_mapSeries, __, arg1))
: _mapSeries(arg0, arg1)
}
/**
* @name _mapPool
*
* @synopsis
* ```coffeescript [specscript]
* type Mappable = Array|Object|Set|Map
*
* _mapPool(collection Mappable, concurrency number, f function) -> result Promise|Mappable
* ```
*/
const _mapPool = function (collection, concurrency, f) {
if (isArray(collection)) {
return arrayMapPool(collection, concurrency, f)
}
if (collection == null) {
throw new TypeError(`invalid collection ${collection}`)
}
if (typeof collection == 'string' || collection.constructor == String) {
return stringMapPool(collection, concurrency, f)
}
if (collection.constructor == Set) {
return setMapPool(collection, concurrency, f)
}
if (collection.constructor == Map) {
return mapMapPool(collection, concurrency, f)
}
if (collection.constructor == Object) {
return objectMapPool(collection, concurrency, f)
}
throw new TypeError(`invalid collection ${collection}`)
}
/**
* @name map.pool
*
* @synopsis
* ```coffeescript [specscript]
* type Mappable = Array|Object|Set|Map
*
* map.pool(
* concurrency number,
* mapper (value any)=>Promise|any,
* )(collection Mappable) -> result Promise|Array
*
* map.pool(
* collection Mappable,
* concurrency number,
* mapper (value any)=>Promise|any,
* ) -> result Promise|Array
* ```
*
* @description
* [map](/docs/map) with limited [concurrency](https://web.mit.edu/6.005/www/fa14/classes/17-concurrency/).
*
* ```javascript [playground]
* const ids = [1, 2, 3, 4, 5]
*
* const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
*
* const delayedIdentity = async value => {
* await sleep(1000)
* return value
* }
*
* map.pool(2, pipe([
* delayedIdentity,
* console.log,
* ]))(ids)
* ```
*
* Any promises passed in argument position are resolved for their values before further execution. This only applies to the eager version of the API.
*
* ```javascript [playground]
* const asyncSquare = async n => n ** 2
*
* map.pool(Promise.resolve([1, 2, 3, 4, 5]), 5, asyncSquare).then(console.log)
* // [1, 4, 9, 16, 25]
* ```
*
* @TODO objectMapPool
*
* @execution concurrent
*/
map.pool = function mapPool(arg0, arg1, arg2) {
if (arg2 == null) {
return curry3(_mapPool, __, arg0, arg1)
}
return isPromise(arg0)
? arg0.then(curry3(_mapPool, __, arg1, arg2))
: _mapPool(arg0, arg1, arg2)
}
/**
* @name map.rate
*
* @synopsis
* ```coffeescript [specscript]
* type Mappable = Array|Object|Set|Map
*
* map.rate(
* rate number,
* f (value any)=>Promise|any,
* )(collection Mappable) -> result Promise|Array
*
* map.rate(
* collection Mappable,
* rate number,
* f (value any)=>Promise|any,
* ) -> result Promise|Array
* ```
*/
module.exports = map