var.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { VAR_ITEM_TEMPLATE, getMaxVarNameLength, zhRegex, emojiRegex, MAX_VAR_KEY_LENGHT } from "@/config"
  2. const otherAllowedRegex = new RegExp(`^[a-zA-Z0-9_]+$`)
  3. export const getNewVar = (key: string) => {
  4. return {
  5. ...VAR_ITEM_TEMPLATE,
  6. key,
  7. name: key.slice(0, getMaxVarNameLength(key)),
  8. }
  9. }
  10. const checkKey = (key: string, canBeEmpty?: boolean) => {
  11. if (key.length === 0 && !canBeEmpty) {
  12. return 'canNoBeEmpty'
  13. }
  14. if (canBeEmpty && key === '') {
  15. return true
  16. }
  17. if (key.length > MAX_VAR_KEY_LENGHT) {
  18. return 'tooLong'
  19. }
  20. if (otherAllowedRegex.test(key)) {
  21. if (/[0-9]/.test(key[0])) {
  22. return 'notStartWithNumber'
  23. }
  24. return true
  25. }
  26. return 'notValid'
  27. }
  28. export const checkKeys = (keys: string[], canBeEmpty?: boolean) => {
  29. let isValid = true
  30. let errorKey = ''
  31. let errorMessageKey = ''
  32. keys.forEach((key) => {
  33. if (!isValid) {
  34. return
  35. }
  36. const res = checkKey(key, canBeEmpty)
  37. if (res !== true) {
  38. isValid = false
  39. errorKey = key
  40. errorMessageKey = res
  41. }
  42. })
  43. return { isValid, errorKey, errorMessageKey }
  44. }