@wxhccc/es-util 1.7.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2019 hjw
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1
+ MIT License
2
+
3
+ Copyright (c) 2019 hjw
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
21
  SOFTWARE.
package/README.md CHANGED
@@ -1,26 +1,30 @@
1
1
  ## Es Utils library
2
2
 
3
- **es-util** is a useful methods library, contain some functions we might need in a project which based on ES
3
+ is a useful methods library, contain some functions you might need in a project which based on ES
4
4
 
5
+ > 2.0 has broken update, see module for detail
5
6
 
6
7
  # Installation
7
8
 
8
9
  #### npm
9
10
  ```shell
10
- $ npm install @wxhccc/es-util --save
11
+ $ npm install @wxhccc/es-util
11
12
  ```
13
+ #### yarn
14
+ ```shell
15
+ $ yarn add @wxhccc/es-util
16
+ ```
17
+
12
18
  #### in browser
13
19
 
14
20
  `<script src="https://cdn.jsdelivr.net/npm/@wxhccc/es-util/lib/index.min.js"></script>`
15
21
 
16
22
  # Usage
17
23
 
18
- #### in webpack or node
19
-
20
24
  ```javascript
21
- import * as EsUtil from 'es-util'
22
- // or import { xxx } from 'es-util'
23
- // or const EsUtil = require('es-util')
25
+ import * as EsUtil from '@wxhccc/es-util'
26
+ // or import { xxx } from '@wxhccc/es-util'
27
+ // or const EsUtil = require('@wxhccc/es-util')
24
28
 
25
29
  // example, array2tree
26
30
  const array = [
@@ -59,18 +63,19 @@ console.log(EsUtil.array2tree)
59
63
 
60
64
  ## array-tree-switch module
61
65
 
62
- ### `array2tree(array, options)`
66
+ ### `array2tree(array, options)`
63
67
 
64
68
  transform an array to tree structure
65
69
 
66
70
  **parameters:**
67
- - **array** {Array} The array need to transform.
71
+ - **array** {Array} (The array need to transform).
68
72
  - **options** {Object} The options.
69
- - **options.primaryKey** {String} the primary key of array item, default `'id'`
70
- - **options.parentKey** {String} the parent key of array item, default `'pid'`
71
- - **options.childrenKey** {String} the childrenKey key of tree structure node, default `'children'`
72
- - **options.createRoot** {Boolean/Function} whether to create a root node, default `'false'`, will return an array, if `'true'` ,will return an object. you can pass an function as well, the transformed array will pass to function
73
- - **options.parentRefKey** {Boolean/String} whether to create a reference of current node's parent, default `'false'`, will do nothing. if you set it to string or `'true'(mean '_parent')` ,will use it as the object key which point to the parent node of current node.
73
+ - **primaryKey** {String} the primary key of array item, default `'id'`
74
+ - **parentKey** {String} the parent key of array item, default `'pid'`
75
+ - **childrenKey** {String} the childrenKey key of tree structure node, default `'children'`
76
+ - **createRoot** {Boolean/Function} whether to create a root node, default `'false'`, will return an array, if `'true'` ,will return an object. you can pass an function as well, the transformed array will pass to function
77
+ - **parentRefKey** {Boolean/String} whether to create a reference of current node's parent, default `'false'`, will do nothing. if you set it to string or `'true'(mean '_parent')` ,will use it as the object key which point to the parent node of current node.
78
+
74
79
  >warning: set the `parentRefKey` will make the return tree object/array cycling, so you can't use `JSON.stringify` to stringify it
75
80
 
76
81
  **returns**: array or object with tree structure.
@@ -78,7 +83,7 @@ transform an array to tree structure
78
83
  Example
79
84
 
80
85
  ```javascript
81
- import { array2tree } from 'es-util'
86
+ import { array2tree } from '@wxhccc/es-util'
82
87
 
83
88
  const array = [
84
89
  { id: 1, parentId: 0, name: 'language' },
@@ -164,10 +169,10 @@ transform tree structure to an array
164
169
  **parameters:**
165
170
  - **tree** {Array/Object} The tree structure need to transform.
166
171
  - **options** {Object} The options.
167
- - **options.primaryKey** {String} the primary key of node item, default `'id'`
168
- - **options.parentKey** {String} the parent key of node item, default `'pid'`
169
- - **options.childrenKey** {String} the childrenKey key of node item, default `'children'`
170
- - **options.hasParentKey** {Boolean} whether tree node has parent property, default `'true'`, if `'false'` ,will add an parent key property
172
+ - **primaryKey** {String} the primary key of node item, default `'id'`
173
+ - **parentKey** {String} the parent key of node item, default `'pid'`
174
+ - **childrenKey** {String} the childrenKey key of node item, default `'children'`
175
+ - **hasParentKey** {Boolean} whether tree node has parent property, default `'true'`, if `'false'` ,will add an parent key property
171
176
 
172
177
 
173
178
  **returns**: items array
@@ -175,7 +180,7 @@ transform tree structure to an array
175
180
  Example
176
181
 
177
182
  ```javascript
178
- import { tree2array } from 'es-util'
183
+ import { tree2array } from '@wxhccc/es-util'
179
184
 
180
185
  const tree = {
181
186
  id: 0,
@@ -227,7 +232,7 @@ Check whether the Chinese id number provided is valid
227
232
  Example
228
233
 
229
234
  ```javascript
230
- import { ChinaIdCardValid } from 'es-util'
235
+ import { ChinaIdCardValid } from '@wxhccc/es-util'
231
236
 
232
237
 
233
238
  console.log(ChinaIdCardValid('[valid IDcard]')
@@ -252,7 +257,7 @@ Check whether the formulaString provided is valid
252
257
  Example
253
258
 
254
259
  ```javascript
255
- import { formulaValidate } from 'es-util'
260
+ import { formulaValidate } from '@wxhccc/es-util'
256
261
 
257
262
 
258
263
  console.log(formulaValidate('A+B*(D-C/E)')
@@ -282,7 +287,7 @@ create an object from an object array.
282
287
  Example
283
288
 
284
289
  ```javascript
285
- import { mapToObject } from 'es-util'
290
+ import { mapToObject } from '@wxhccc/es-util'
286
291
 
287
292
  const array = [
288
293
  { key: 'a', value: 'b', name: 'afsfsdfe' },
@@ -306,17 +311,14 @@ checkout an array from an object by gived keys, you can merge new data to object
306
311
  **parameters:**
307
312
  - **object** {Object} The source object.
308
313
  - **keys** {Array/Object} The properties array of `object`. or an object contains keys which you want to pick from `object` and values you want to merge to those picked values. if keys not provided, will return `Object.values(object)`
309
- - **mergeFn** {Function} this method use `Object.assign` to merge values where two value are object, you can provide custom function to merge value.
310
- - **empty** {Object} empty object
311
- - **objectValue** {Object} the value of object[keyitem]
312
- - **keysValue** {Object} the value of keys[keyitem]
314
+ - **mergeFn** {Function} this method use `Object.assign` to merge values where two value are object default, you can provide custom function to merge value.
313
315
 
314
316
  **returns**: array
315
317
 
316
318
  Example
317
319
 
318
320
  ```javascript
319
- import { checkoutBy } from 'es-util'
321
+ import { checkoutBy } from '@wxhccc/es-util'
320
322
 
321
323
  const configs = {
322
324
  a: { key: 1, name: 'afsfsdfe' },
@@ -352,7 +354,7 @@ pick and rename object's keys
352
354
  Example
353
355
 
354
356
  ```javascript
355
- import { pickRenameKeys } from 'es-util'
357
+ import { pickRenameKeys } from '@wxhccc/es-util'
356
358
 
357
359
  const configs = {
358
360
  a: { name: 'afsfsdfe' },
@@ -375,10 +377,10 @@ transform byte size to a string in the specified format
375
377
  **parameters:**
376
378
  - **byteNum** {Number} The size number need to transform.
377
379
  - **options** {Object} The options.
378
- - **options.standard** {String} the standard used to transform, default `'jedec'`, suport `'metric'`, `'iec'`. [Metric, IEC and JEDEC units](https://en.wikipedia.org/wiki/Gigabyte)
379
- - **options.unitLvl** {String} the unit lvl to transform byte size, default `'auto'`. suport `'B','K','M','G','T','P','E','Z','Y'`
380
- - **options.precision** {Number} the precision of value, default `1`
381
- - **options.detail** {Boolean} whether to return an object of detai info, default `false`.
380
+ - **standard** {String} the standard used to transform, default `'jedec'`, suport `'metric'`, `'iec'`. [Metric, IEC and JEDEC units](https://en.wikipedia.org/wiki/Gigabyte)
381
+ - **unitLvl** {String} the unit lvl to transform byte size, default `'auto'`. suport `'B','K','M','G','T','P','E','Z','Y'`
382
+ - **precision** {Number} the precision of value, default `1`
383
+ - **detail** {Boolean} whether to return an object of detai info, default `false`.
382
384
 
383
385
 
384
386
  **returns**: string or object
@@ -386,7 +388,7 @@ transform byte size to a string in the specified format
386
388
  Example
387
389
 
388
390
  ```javascript
389
- import { byteStringify } from 'es-util'
391
+ import { byteStringify } from '@wxhccc/es-util'
390
392
 
391
393
  byteStringify(1234)
392
394
  /*log '1.2 KB'*/
@@ -414,46 +416,176 @@ byteStringify(1234, { detail: true, standard: 'metric', precision: 3 })
414
416
 
415
417
  wrap promise with then and catch to return `[null, data]` or `[Error, undefined]`, useful async & await
416
418
 
419
+ Example
420
+
421
+ ```javascript
422
+ import { awaitWrapper } from '@wxhccc/es-util'
423
+
424
+ const [err, data] = await awaitWrapper(Promise.resolve(1))
425
+ /*log [null, 1] */
426
+ const [err, data] = await awaitWrapper(Promise.reject())
427
+ /*log [err, undefined] */
428
+
429
+ ```
430
+
417
431
  ### `wp(promise, [wrap])`
418
432
 
433
+ > this module has been refactor in v2.0,no longer support vue/react instance detection because there is no need in hooks.
434
+
419
435
  wrap promise or a function return promise with lock method to control UI or forbiden multi task at same time
420
436
 
421
437
  **parameters:**
422
438
  - **promise** {Promise|() => Promise} promise object or a function return promise object. when use function and lock, it can prevent second call before previous promise settled
423
- - **wrapOrOptions** {boolean|WrapOptions} shortcut of `wrap` option or full options.
439
+ - **options** {boolean|WrapOptions} shortcut of `wrap` option or full options.
424
440
  - **wrap** {boolean} whether use `awaitWrapper` to wrap then promise.
425
- - **lock** {string|(bool) => void|[ref, lockKey]}
426
- string: property(support nested) used to lock. useful in vue instance and React Class component
427
-
441
+ - **lock** {(bool) => void | [ref, lockKey]}
428
442
  function: useful in ReactHook component, pass setXXX to method
429
443
 
430
444
  syncRefHandle: an array such as `[object, keyOfObject]` useful when need to lock promise when value can't be update sync, such as React
431
445
  - **syncRefHandle** {[ref, lockKey]} when you need function and syncRefHandle at sametime
432
- - **manualUnlock** {boolean} whether not unlock automatic
433
446
 
434
447
  **returns**: a extends promise object with `__lockValue` getter and `unlock` method
435
448
 
436
- > can be use in react and vue2/3 instance when bind this
449
+ > ~~can be use in react and vue2/3 instance when bind this~~
450
+ > 2.0 will not bind this
437
451
 
438
- ### `wpVuePlugin`
439
452
 
440
- an plugin object for vue
453
+ #### use in react hooks
441
454
 
455
+ ```javascript
456
+ import { wp } from '@wxhccc/es-util'
457
+
458
+ const [loading, setLoading] = useState(false)
459
+
460
+ /**
461
+ * eg.1
462
+ * will run setLoading(true) and run setLoading(false) after promise resettled
463
+ **/
464
+ const result = await wp(Promise.resolve(1), { lock: setLoading })
465
+ /**
466
+ * eg.2
467
+ */
468
+ const [er, data] = await wp(Promise.resolve(1), { wrap: true, lock: setLoading })
469
+ /*log [null, 1] */
470
+
471
+ /**
472
+ * eg.3
473
+ * will prevent second run when use syncRefHandle
474
+ */
475
+ const loadingRef = useRef(false)
476
+
477
+ const asyncMethod = () => Promise.resolve(1)
478
+
479
+ const runTask = async () => {
480
+ const [err, data] = await wp(asyncMethod, { wrap: true, lock: setLoading, syncRefHandle: [loadingRef, 'current'] })
481
+ }
482
+
483
+ runTask()
484
+ runTask()
485
+ /*log [null, 1] */
486
+ /*log [null, undefined], second method call will resolve undefined immediate, but not run asyncMethod */
487
+
488
+ ```
489
+
490
+ #### use in vue setup
491
+
492
+ ```javascript
493
+ import { wp } from '@wxhccc/es-util'
494
+
495
+ const loading = ref(false)
496
+
497
+ /**
498
+ * eg.1
499
+ * will run setLoading(true) and run setLoading(false) after promise resettled
500
+ **/
501
+ const setLoading = (bool) => loading.value = bool
502
+ const result = await wp(Promise.resolve(1), { lock: setLoading })
503
+ /**
504
+ * eg.2
505
+ * lock can be syncRefHandle if ref is update sync, it's more simpler for vue
506
+ */
507
+ const asyncMethod = () => Promise.resolve(1)
508
+
509
+ const runTask = async () => {
510
+ const [err, data] = await wp(asyncMethod, { wrap: true, lock: [loading, 'value'] })
511
+ }
512
+
513
+ runTask()
514
+ runTask()
515
+ /*log [null, 1] */
516
+ /*log [null, undefined], second method call will resolve undefined immediate, but not run asyncMethod */
517
+
518
+ ```
442
519
 
443
520
  ## event-target-emitter module
444
521
 
445
522
  > v1.7.0 add
446
523
 
524
+ this is a simple event emitter, you can find other emitter package is you need more function
525
+
447
526
  ### `eventTargetEmitter(options)`
448
527
 
449
- return an emitter instance with `on`, `off` and some other methods to handle with EventTarget
528
+ return an emitter instance with `on`, `off`, `emit` and some other methods to handle with EventTarget
450
529
 
451
530
  **parameters:**
452
531
  - **options** {ConfigOptions}
453
532
  - **name** {string} the name of current emitter. can used to limit message received from
454
533
  - **customHanlderCreator** {(watchers) => Function} custome handler creator, you can handle message distribute logic as you want.
455
534
 
456
- ## event-target-emitter module
535
+ ```javascript
536
+ import { eventTargetEmitter } from '@wxhccc/es-util'
537
+
538
+ /** eg.1 */
539
+ const emitter = eventTargetEmitter()
540
+
541
+ const runTaskA = () => {
542
+ console.log('a')
543
+ }
544
+ const runTaskB = () => {
545
+ console.log('b')
546
+ }
547
+ emitter.on('to-run-a', runTaskA)
548
+ emitter.on('to-run-b', runTaskA)
549
+
550
+ ...
551
+ websocket.on('message', (task) => {
552
+ if (task === 'a') {
553
+ emitter.emit('to-run-a')
554
+ } else if (task === 'b') {
555
+ emitter.emit('to-run-b')
556
+ }
557
+ })
558
+
559
+ /** eg.2 */
560
+ // page-a in tab 1
561
+ const emitter = eventTargetEmitter({ name: 'page-a' })
562
+
563
+ const runTask = () => {
564
+ // this method will call when received message from page-b, but not call when received message from page-c
565
+ console.log('do someting')
566
+ }
567
+ emitter.on('to-run-task', runTask, { limitFrom: 'page-b' })
568
+
569
+ const onStorageMessage = (payload) => {
570
+ const payload = JSON.parse(localStorage.setItem('page-communicate'))
571
+ emitter.emit(payload)
572
+ }
573
+
574
+ window.addEventListener('storage', onStorageMessage)
575
+
576
+ // page-b in tab 2
577
+ const { createPayload } = eventTargetEmitter({ name: 'page-b' })
578
+
579
+ const payload = createPayload('to-run-task', { a: 1 })
580
+ /**
581
+ * payload: { method: 'to-run-task', data: { a: 1 }, originEmitterName: 'page-b' }
582
+ */
583
+ localStorage.setItem('page-communicate', payload)
584
+
585
+ //
586
+ ```
587
+
588
+ ## page-communicate module
457
589
 
458
590
  > v1.7.0 add
459
591
 
@@ -461,5 +593,77 @@ return an emitter instance with `on`, `off` and some other methods to handle wit
461
593
 
462
594
  return an instance which can used to communicate between same-origin pages, powered by `eventTargetEmitter`
463
595
 
596
+ this module is full realize of `eventTargetEmitter` eg.2, it use `BroadcastChannel` if it supported, otherwise will use `window.localStorage
597
+
598
+ ```javascript
599
+ import { pageCommunicate } from '@wxhccc/es-util'
600
+
601
+ const pc = pageCommunicate()
602
+
603
+ pc.on('update-use-info', (newUserInfo) => {
604
+ // update global state
605
+ })
606
+
607
+ // when one page change login account
608
+ pc.send('update-use-info', newUserInfo)
609
+ ```
610
+
611
+
612
+ ## raf-timer module
613
+
614
+ > v2.0.0 add
615
+
616
+ ### `createRAFTimer(options)`
617
+
618
+ return an requestAnimationFrame timer instance. used to instead of window.setTimout and window.setInterval.
619
+
620
+ ```javascript
621
+ import { createRAFTimer } from '@wxhccc/es-util'
622
+
623
+ const timer = createRAFTimer()
624
+ // start timer
625
+ timer.start()
626
+
627
+ /** mock window.setTimeout, run once */
628
+ timer.addTask(() => {
629
+ console.log('run after 1 second')
630
+ }, 1000, 1)
631
+ /** run 10 times */
632
+ timer.addTask(() => {
633
+ console.log('run every 1 second, max 10 times')
634
+ }, 1000, 10)
635
+
636
+ const fn = () => {}
637
+ /** mock window.setInterval */
638
+ timer.addTask(fn, 1000)
639
+ /** stop task */
640
+ timer.removeTask(fn)
641
+
642
+ // you can stop timer when no task by pass options
643
+ const timer = createRAFTimer({
644
+ autoStopWhenNoTask: true,
645
+ autoStartWhenAddTask: true
646
+ })
647
+
648
+ ```
649
+
650
+ ## date-time module
651
+
652
+ > v2.0.0 add
653
+
654
+ ### `secondsToDuration(number, maxUnit)`
655
+
656
+ ```javascript
657
+ import { secondsToDuration } from '@wxhccc/es-util'
658
+
659
+ const detail = secondsToDuration(12345678)
660
+ /*log {h: 3429, m: 21, s: 18} */
661
+
662
+ const detail = secondsToDuration(12345678, 'd')
663
+ /*log { d: 142, h: 21, m: 21, s: 18 } */
664
+ ```
665
+
666
+ parse seconds to duration detail object
667
+
464
668
  ## License
465
669
  MIT
@@ -1,3 +1,4 @@
1
+ import { AnyFunction } from './types';
1
2
  export interface Node {
2
3
  [key: string]: any;
3
4
  }
@@ -30,7 +31,17 @@ declare type Tree = TreeNode[] | {
30
31
  * @param {boolean | Function} createNode whether create root node, or function which can return root node
31
32
  * @param {boolean | string} parentRefKey parent reference key of node
32
33
  */
33
- export declare function array2tree(array: Node[], options?: TreeOptions): Tree;
34
+ export declare function array2tree(array: Node[], options?: TreeOptions & {
35
+ createNode?: false;
36
+ }): TreeNode[];
37
+ export declare function array2tree(array: Node[], options: TreeOptions & {
38
+ createNode: true;
39
+ }): {
40
+ [children: string]: TreeNode[];
41
+ };
42
+ export declare function array2tree<T = any>(array: Node[], options: TreeOptions & {
43
+ createNode: AnyFunction<T>;
44
+ }): T;
34
45
  declare type Nodes = Node[];
35
46
  declare type NodeMap = {
36
47
  [id: string]: Node;
@@ -45,5 +56,10 @@ declare type NodeMap = {
45
56
  * @param {boolean} hasParentKey whether create parent id in node
46
57
  * @param {boolean} returnObject whether return object or array
47
58
  */
48
- export declare function tree2array(tree: Tree, options?: NodeOptions): NodeMap | Nodes;
59
+ export declare function tree2array(tree: Tree, options?: NodeOptions & {
60
+ returnObject?: false;
61
+ }): Nodes;
62
+ export declare function tree2array(tree: Tree, options: NodeOptions & {
63
+ returnObject: true;
64
+ }): NodeMap;
49
65
  export {};
@@ -0,0 +1,14 @@
1
+ export declare type TimeUnitShort = 'd' | 'h' | 'm' | 's';
2
+ export interface DurationDetail {
3
+ d?: number;
4
+ h?: number;
5
+ m?: number;
6
+ s: number;
7
+ }
8
+ /**
9
+ * 将秒数转换为时间段对象
10
+ * @param number 秒数
11
+ * @param maxUnit 最大的单位,默认是小时
12
+ * @returns DurationDetail
13
+ */
14
+ export declare const secondsToDuration: (number: number, maxUnit?: Exclude<TimeUnitShort, 's'>) => DurationDetail;
@@ -1,4 +1,4 @@
1
- import { AnyFunction } from "./types";
1
+ import { AnyFunction } from './types';
2
2
  export interface EventPayload<T = any> {
3
3
  /** method name to be listenered */
4
4
  method: string;
@@ -22,7 +22,7 @@ export interface BindOptions {
22
22
  /** 事件所在命名空间 */
23
23
  namespace?: string;
24
24
  }
25
- export declare const NOMETHOD: symbol;
25
+ export declare const NOMETHOD: unique symbol;
26
26
  /**
27
27
  * 创建emitter形式的实例,可以通过实例封装事件对象,比如websocket,得到一个更便捷的方法,具体可参考page-communicate.js文件内容
28
28
  * @param options 配置项
@@ -31,15 +31,15 @@ export declare const NOMETHOD: symbol;
31
31
  export declare function eventTargetEmitter(options?: ConfigOptions): {
32
32
  name: string | undefined;
33
33
  rootEventListener: <T = any>(payload: EventPayload<T>) => void;
34
- on: <T_1>(method: string | symbol, listener: (data: T_1) => any, options?: BindOptions | undefined) => void;
35
- off: (method: string | symbol, callback?: AnyFunction<any> | undefined, options?: BindOptions | undefined) => void;
34
+ on: <T_1>(method: string | symbol, listener: (data: T_1) => any, options?: BindOptions) => void;
35
+ off: (method: string | symbol, callback?: AnyFunction, options?: BindOptions) => void;
36
36
  emit: (methodOrPayload: string | EventPayload<any>, data?: any, target?: string | undefined) => void;
37
- createPayload: (methodOrPayload: string | EventPayload, data?: any, target?: string | undefined) => EventPayload<any>;
37
+ createPayload: (methodOrPayload: string | EventPayload, data?: any, target?: string) => EventPayload<any>;
38
38
  removeAllListeners: () => void;
39
39
  getMethodNames: {
40
- (all?: false | undefined): string[];
40
+ (all?: false): string[];
41
41
  (all: true): string[][];
42
42
  };
43
- getListeners: (method: string | symbol, options?: BindOptions | undefined) => AnyFunction<any>[];
43
+ getListeners: (method: string | symbol, options?: BindOptions) => AnyFunction<any>[];
44
44
  };
45
45
  export default eventTargetEmitter;
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * @wxhccc/es-util v1.7.0
2
+ * @wxhccc/es-util v2.0.0
3
3
  * (c) 2022 wxhccc
4
4
  * @license MIT
5
5
  */
@@ -7,6 +7,8 @@
7
7
 
8
8
  Object.defineProperty(exports, '__esModule', { value: true });
9
9
 
10
+ var utils = require('./utils.js');
11
+
10
12
  const isStr = (val) => typeof val === 'string';
11
13
  const NOMETHOD = Symbol('NOMETHOD');
12
14
  /**
@@ -17,7 +19,9 @@ const NOMETHOD = Symbol('NOMETHOD');
17
19
  function eventTargetEmitter(options) {
18
20
  const watchers = new Map([[NOMETHOD, new Set()]]);
19
21
  const { name: currentName, customHanlderCreator } = options || {};
20
- const customHanlder = customHanlderCreator instanceof Function ? customHanlderCreator(watchers) : null;
22
+ const customHanlder = utils.isFn(customHanlderCreator)
23
+ ? customHanlderCreator(watchers)
24
+ : null;
21
25
  const splitRegExp = /\|-[a-z]+-\|/;
22
26
  const listenerSafeRun = (listener, ...args) => {
23
27
  try {
@@ -33,25 +37,28 @@ function eventTargetEmitter(options) {
33
37
  const matchListeners = [];
34
38
  watchers.forEach((value, key) => {
35
39
  if (typeof key === 'string' && key.startsWith(method)) {
36
- const [, eFrom,] = key.split(splitRegExp);
40
+ const [, eFrom] = key.split(splitRegExp);
37
41
  if (!eFrom || !from || eFrom === from) {
38
42
  matchListeners.push(...value);
39
43
  }
40
44
  }
41
45
  });
42
- if (matchListeners.length && (!currentName || !to || currentName === to)) {
43
- matchListeners.forEach(listener => listenerSafeRun(listener, data));
46
+ if (matchListeners.length &&
47
+ (!currentName || !to || currentName === to)) {
48
+ matchListeners.forEach((listener) => listenerSafeRun(listener, data));
44
49
  }
45
50
  }
46
51
  const noMethodListeners = watchers.get(NOMETHOD);
47
52
  if (noMethodListeners) {
48
- noMethodListeners.forEach(listener => listenerSafeRun(listener, data, payload));
53
+ noMethodListeners.forEach((listener) => listenerSafeRun(listener, data, payload));
49
54
  }
50
55
  };
51
- const rootEventListener = customHanlder instanceof Function ? customHanlder : defaultHanlder;
56
+ const rootEventListener = utils.isFn(customHanlder) ? customHanlder : defaultHanlder;
52
57
  const getFullMethodName = (method, options) => {
53
58
  const { limitFrom = '', namespace = '' } = options || {};
54
- return (limitFrom || namespace) && typeof method === 'string' ? `${method}|-from-|${limitFrom}|-ns-|${namespace}` : method;
59
+ return (limitFrom || namespace) && typeof method === 'string'
60
+ ? `${method}|-from-|${limitFrom}|-ns-|${namespace}`
61
+ : method;
55
62
  };
56
63
  const on = (method, listener, options) => {
57
64
  if (typeof method === 'symbol' && method !== NOMETHOD) {
@@ -68,7 +75,7 @@ function eventTargetEmitter(options) {
68
75
  if (typeof method === 'symbol' && method !== NOMETHOD) {
69
76
  return;
70
77
  }
71
- const { limitFrom, namespace } = options || {};
78
+ const { namespace } = options || {};
72
79
  if (namespace && !method) {
73
80
  watchers.forEach((_value, key) => {
74
81
  if (typeof key === 'string' && key.endsWith(namespace)) {
@@ -88,12 +95,16 @@ function eventTargetEmitter(options) {
88
95
  watchers.clear();
89
96
  };
90
97
  const createPayload = (methodOrPayload, data, target) => {
91
- return isStr(methodOrPayload) ? {
92
- method: methodOrPayload,
93
- data,
94
- ...(target && isStr(target) ? { targetEmitterName: target } : {}),
95
- ...(currentName && isStr(currentName) ? { originEmitterName: currentName } : {})
96
- } : methodOrPayload;
98
+ return isStr(methodOrPayload)
99
+ ? {
100
+ method: methodOrPayload,
101
+ data,
102
+ ...(target && isStr(target) ? { targetEmitterName: target } : {}),
103
+ ...(currentName && isStr(currentName)
104
+ ? { originEmitterName: currentName }
105
+ : {})
106
+ }
107
+ : methodOrPayload;
97
108
  };
98
109
  const emit = (...args) => {
99
110
  const payload = createPayload(...args);
@@ -118,9 +129,19 @@ function eventTargetEmitter(options) {
118
129
  const listeners = watchers.get(trueMethod);
119
130
  return listeners ? Array.from(listeners) : [];
120
131
  };
121
- return { name: currentName, rootEventListener, on, off, emit, createPayload, removeAllListeners, getMethodNames, getListeners };
132
+ return {
133
+ name: currentName,
134
+ rootEventListener,
135
+ on,
136
+ off,
137
+ emit,
138
+ createPayload,
139
+ removeAllListeners,
140
+ getMethodNames,
141
+ getListeners
142
+ };
122
143
  }
123
144
 
124
145
  exports.NOMETHOD = NOMETHOD;
125
- exports.default = eventTargetEmitter;
146
+ exports["default"] = eventTargetEmitter;
126
147
  exports.eventTargetEmitter = eventTargetEmitter;