Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

endent.js 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. const dedent = require('dedent')
  2. const objectorarray = require('objectorarray')
  3. const parse = require('fast-json-parse')
  4. module.exports = endent
  5. const ENDENT_ID = 'twhZNwxI1aFG3r4'
  6. function endent (strings, ...values) {
  7. const raw = typeof strings === 'string' ? [strings] : strings.raw
  8. let result = ''
  9. for (let i = 0; i < raw.length; i++) {
  10. result += raw[i]
  11. if (i < values.length) {
  12. let value = values[i]
  13. let isJson = false
  14. if (parse(value).value) {
  15. value = parse(value).value
  16. isJson = true
  17. }
  18. if ((value && value[ENDENT_ID]) || isJson) {
  19. let rawlines = result.split('\n')
  20. let l = rawlines[rawlines.length - 1].search(/\S/)
  21. let endentation = l > 0 ? ' '.repeat(l) : ''
  22. let valueJson = isJson ? JSON.stringify(value, null, 2) : value[ENDENT_ID]
  23. let valueLines = valueJson.split('\n')
  24. valueLines.forEach((l, index) => {
  25. if (index > 0) {
  26. result += ('\n' + endentation + l)
  27. } else {
  28. result += l
  29. }
  30. })
  31. } else if (typeof value === 'string' && value.includes('\n')) {
  32. let endentations = result.match(/(?:^|\n)( *)$/)
  33. if (typeof value === 'string') {
  34. let endentation = endentations ? endentations[1] : ''
  35. result += value
  36. .split('\n')
  37. .map((str, i) => {
  38. str = (ENDENT_ID + str)
  39. return i === 0 ? str : `${endentation}${str}`
  40. })
  41. .join('\n')
  42. } else {
  43. result += value
  44. }
  45. } else {
  46. result += value
  47. }
  48. }
  49. }
  50. result = dedent(result)
  51. return result.split(ENDENT_ID).join('')
  52. }
  53. endent.pretty = (data) => {
  54. return objectorarray(data) ? {[ENDENT_ID]: JSON.stringify(data, null, 2)} : data
  55. }