Note that these are very basic tests and just a start to learn vitest. There are no tests for DOM/Window because I do not know how to do those tests the best way with some headless brower testing suit or which to use
38 lines
823 B
JavaScript
38 lines
823 B
JavaScript
/*
|
|
Description: Generate unique ids
|
|
Date: 2025/3/7
|
|
Creator: Clemens Schwaighofer
|
|
*/
|
|
|
|
export { generateId, randomIdF };
|
|
|
|
|
|
/**
|
|
* generateId :: Integer -> String
|
|
* only works on mondern browsers
|
|
* @param {Number} len length of unique id string
|
|
* @return {String} random string in length of len
|
|
*/
|
|
function generateId(len)
|
|
{
|
|
var arr = new Uint8Array((len || 40) / 2);
|
|
(
|
|
window.crypto ||
|
|
// @ts-ignore
|
|
window.msCrypto
|
|
).getRandomValues(arr);
|
|
return Array.from(arr, self.dec2hex).join('');
|
|
}
|
|
|
|
/**
|
|
* creates a pseudo random string of 10 or 11 characters
|
|
* works on all browsers
|
|
* after many runs it will create duplicates
|
|
* NOTE: no idea why this sometimes returns 10 or 11
|
|
* @return {String} not true random string
|
|
*/
|
|
function randomIdF()
|
|
{
|
|
return Math.random().toString(36).substring(2);
|
|
}
|