@wordpress/compose
Version:
WordPress higher-order components (HOCs).
57 lines (52 loc) • 1.51 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _element = require("@wordpress/element");
/**
* WordPress dependencies
*/
const instanceMap = new WeakMap();
/**
* 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) {
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
*
* @param object Object reference to create an id for.
*/
/**
* 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, prefix, preferredId) {
return (0, _element.useMemo)(() => {
if (preferredId) {
return preferredId;
}
const id = createId(object);
return prefix ? `${prefix}-${id}` : id;
}, [object, preferredId, prefix]);
}
var _default = exports.default = useInstanceId;
//# sourceMappingURL=index.js.map
;