25 lines
807 B
JavaScript
25 lines
807 B
JavaScript
//@ts-check
|
|
import {getReasonableUuid} from "./getReasonableUuid.mjs"
|
|
|
|
/**
|
|
* Returns an id that is guaranteed to not exist in the current loaded page.
|
|
* Only usable in the browser, after the page has loaded.
|
|
* Using it outside the browser or prior to loading will yield a pseudo-unique id,
|
|
* but not guaranteed unique.
|
|
* Ids are deterministic, so calling this function in the same order will always return
|
|
* the same set of ids.
|
|
* @see {uuid}
|
|
* @param {string} prefix any prefix you like, it helps discriminate ids
|
|
*/
|
|
export const getPageUniqueId = (prefix = "") => {
|
|
let id = prefix;
|
|
let limit = 99999;
|
|
while (
|
|
typeof document !== "undefined" &&
|
|
document.getElementById((id = `${prefix}${getReasonableUuid()}`)) &&
|
|
limit-- > 0
|
|
);
|
|
return id;
|
|
};
|
|
|
|
export default getPageUniqueId |