UNPKG

@datadayrepos/js-id-web

Version:

Utils for generating identifiers in javascript browser environment. Using web crypto engine for random number generation.

27 lines (26 loc) 762 B
export const genTimeId = (function genIdFn() { let preKey = `${+new Date()}`; let key = 0; return () => { const curTimestamp = `${+new Date()}`; if (curTimestamp === preKey) { key += 1; } else { key = 0; } preKey = curTimestamp; return `${preKey}x${key}`; }; })(); export function genTimeIdWithRand() { return Date.now().toString(36) + Math.random().toString(36).substr(2, 5); } export function readableId(length = 9) { let id = ''; const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; for (let i = 0; i < length; i++) { id += possible.charAt(Math.floor(Math.random() * possible.length)); } return id; }