formatter.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /**
  2. * 把对象按照 js配置文件的格式进行格式化
  3. * @param obj 格式化的对象
  4. * @param dep 层级,此项无需传值
  5. * @returns {string}
  6. */
  7. function formatConfig(obj, dep) {
  8. dep = dep || 1
  9. const LN = '\n', TAB = ' '
  10. let indent = ''
  11. for (let i = 0; i < dep; i++) {
  12. indent += TAB
  13. }
  14. let isArray = false, arrayLastIsObj = false
  15. let str = '', prefix = '{', subfix = '}'
  16. if (Array.isArray(obj)) {
  17. isArray = true
  18. prefix = '['
  19. subfix = ']'
  20. str = obj.map((item, index) => {
  21. let format = ''
  22. if (typeof item == 'function') {
  23. //
  24. } else if (typeof item == 'object') {
  25. arrayLastIsObj = true
  26. format = `${LN}${indent}${formatConfig(item,dep + 1)},`
  27. } else if ((typeof item == 'number' && !isNaN(item)) || typeof item == 'boolean') {
  28. format = `${item},`
  29. } else if (typeof item == 'string') {
  30. format = `'${item}',`
  31. }
  32. if (index == obj.length - 1) {
  33. format = format.substring(0, format.length - 1)
  34. } else {
  35. arrayLastIsObj = false
  36. }
  37. return format
  38. }).join('')
  39. } else if (typeof obj != 'function' && typeof obj == 'object') {
  40. str = Object.keys(obj).map((key, index, keys) => {
  41. const val = obj[key]
  42. let format = ''
  43. if (typeof val == 'function') {
  44. //
  45. } else if (typeof val == 'object') {
  46. format = `${LN}${indent}${key}: ${formatConfig(val,dep + 1)},`
  47. } else if ((typeof val == 'number' && !isNaN(val)) || typeof val == 'boolean') {
  48. format = `${LN}${indent}${key}: ${val},`
  49. } else if (typeof val == 'string') {
  50. format = `${LN}${indent}${key}: '${val}',`
  51. }
  52. if (index == keys.length - 1) {
  53. format = format.substring(0, format.length - 1)
  54. }
  55. return format
  56. }).join('')
  57. }
  58. const len = TAB.length
  59. if (indent.length >= len) {
  60. indent = indent.substring(0, indent.length - len)
  61. }
  62. if (!isArray || arrayLastIsObj) {
  63. subfix = LN + indent +subfix
  64. }
  65. return`${prefix}${str}${subfix}`
  66. }
  67. module.exports = {formatConfig}