index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. var util = require('util')
  2. var last = function(str) {
  3. str = str.trim()
  4. return str[str.length-1]
  5. }
  6. var first = function(str) {
  7. return str.trim()[0]
  8. }
  9. var notEmpty = function(line) {
  10. return line.trim()
  11. }
  12. var notEmptyElse = function() {
  13. var notNext = false
  14. return function(line, i, lines) {
  15. if (notNext) {
  16. notNext = false
  17. return ''
  18. }
  19. if (lines[i].trim() === '} else {' && (lines[i+1] || '').trim() === '}') {
  20. notNext = true
  21. return lines[i].replace('} else {', '}')
  22. }
  23. return line
  24. }
  25. }
  26. module.exports = function() {
  27. var lines = []
  28. var indent = 0
  29. var push = function(str) {
  30. var spaces = ''
  31. while (spaces.length < indent*2) spaces += ' '
  32. lines.push(spaces+str)
  33. }
  34. var line = function(fmt) {
  35. if (!fmt) return line
  36. if (fmt.trim()[0] === '}' && fmt[fmt.length-1] === '{') {
  37. indent--
  38. push(util.format.apply(util, arguments))
  39. indent++
  40. return line
  41. }
  42. if (fmt[fmt.length-1] === '{') {
  43. push(util.format.apply(util, arguments))
  44. indent++
  45. return line
  46. }
  47. if (fmt.trim()[0] === '}') {
  48. indent--
  49. push(util.format.apply(util, arguments))
  50. return line
  51. }
  52. push(util.format.apply(util, arguments))
  53. return line
  54. }
  55. line.trim = function() {
  56. lines = lines
  57. .filter(notEmpty)
  58. .map(notEmptyElse())
  59. .filter(notEmpty)
  60. return line
  61. }
  62. line.toString = function() {
  63. return lines.join('\n')
  64. }
  65. line.toFunction = function(scope) {
  66. var src = 'return ('+line.toString()+')'
  67. var keys = Object.keys(scope || {}).map(function(key) {
  68. return key
  69. })
  70. var vals = keys.map(function(key) {
  71. return scope[key]
  72. })
  73. return Function.apply(null, keys.concat(src)).apply(null, vals)
  74. }
  75. if (arguments.length) line.apply(null, arguments)
  76. return line
  77. }