-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathindex.ts
59 lines (53 loc) · 1.54 KB
/
index.ts
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
/**
* WordPress dependencies
*/
import { useMemo } from '@wordpress/element';
const instanceMap = new WeakMap< object, number >();
/**
* Creates a new id for a given object.
*
* @param object Object reference to create an id for.
* @return The instance id (index).
*/
function createId( object: object ): number {
const instances = instanceMap.get( object ) || 0;
instanceMap.set( object, instances + 1 );
return instances;
}
/**
* Specify the useInstanceId *function* signatures.
*
* More accurately, useInstanceId distinguishes between three different
* signatures:
*
* 1. When only object is given, the returned value is a number
* 2. When object and prefix is given, the returned value is a string
* 3. When preferredId is given, the returned value is the type of preferredId
*/
function useInstanceId( object: object ): number;
function useInstanceId( object: object, prefix: string ): string;
function useInstanceId< T extends string | number >(
object: object,
prefix: string,
preferredId?: T
): T;
/**
* Provides a unique instance ID.
*
* @param object Object reference to create an id for.
* @param [prefix] Prefix for the unique id.
* @param [preferredId] Default ID to use.
* @return The unique instance id.
*/
function useInstanceId(
object: object,
prefix?: string,
preferredId?: string | number
): string | number {
return useMemo( () => {
if ( preferredId ) return preferredId;
const id = createId( object );
return prefix ? `${ prefix }-${ id }` : id;
}, [ object ] );
}
export default useInstanceId;