2
0

Common.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. export const copyToCommand = (
  2. value: string,
  3. classSelector?: string,
  4. cb?: () => void
  5. ) => {
  6. const element = classSelector
  7. ? document.querySelector(`.${classSelector}`)
  8. : document.body;
  9. const input = document.createElement('textarea');
  10. input.value = value;
  11. element?.appendChild(input);
  12. input.select();
  13. if (document.execCommand('copy')) {
  14. document.execCommand('copy');
  15. cb && cb();
  16. }
  17. element?.removeChild(input);
  18. };
  19. export const generateId = (prefix = 'id') =>
  20. `${prefix}_${Math.random().toString(36).substr(2, 16)}`;
  21. export const formatNumber = (number: number): string => {
  22. return new Intl.NumberFormat().format(number);
  23. };
  24. /**
  25. * Only use in dev env
  26. * Parent component props is optional but required in child component. Need throw some error
  27. * @param text
  28. */
  29. export const throwErrorForDev = (text: string) => {
  30. throw new Error(text);
  31. };
  32. /**
  33. *
  34. * @param obj key value pair Array
  35. * @param key the target you want to find.
  36. * @returns undefined | string
  37. */
  38. export const findKeyValue = (
  39. obj: { key: string; value: string }[],
  40. key: string
  41. ) => obj.find(v => v.key === key)?.value;
  42. export const generateHashCode = (source: string) => {
  43. let hash = 0,
  44. i,
  45. chr;
  46. if (source.length === 0) return hash;
  47. for (i = 0; i < source.length; i++) {
  48. chr = source.charCodeAt(i);
  49. hash = (hash << 5) - hash + chr;
  50. hash |= 0; // Convert to 32bit integer
  51. }
  52. return hash.toString();
  53. };
  54. export const generateIdByHash = (salt?: string) => {
  55. return generateHashCode(`${new Date().getTime().toString()}-${salt}`);
  56. };