index.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. var util = require('util')
  2. var INDENT_START = /[\{\[]/
  3. var INDENT_END = /[\}\]]/
  4. module.exports = function() {
  5. var lines = []
  6. var indent = 0
  7. var push = function(str) {
  8. var spaces = ''
  9. while (spaces.length < indent*2) spaces += ' '
  10. lines.push(spaces+str)
  11. }
  12. var line = function(fmt) {
  13. if (!fmt) return line
  14. if (INDENT_END.test(fmt.trim()[0]) && INDENT_START.test(fmt[fmt.length-1])) {
  15. indent--
  16. push(util.format.apply(util, arguments))
  17. indent++
  18. return line
  19. }
  20. if (INDENT_START.test(fmt[fmt.length-1])) {
  21. push(util.format.apply(util, arguments))
  22. indent++
  23. return line
  24. }
  25. if (INDENT_END.test(fmt.trim()[0])) {
  26. indent--
  27. push(util.format.apply(util, arguments))
  28. return line
  29. }
  30. push(util.format.apply(util, arguments))
  31. return line
  32. }
  33. line.toString = function() {
  34. return lines.join('\n')
  35. }
  36. line.toFunction = function(scope) {
  37. var src = 'return ('+line.toString()+')'
  38. var keys = Object.keys(scope || {}).map(function(key) {
  39. return key
  40. })
  41. var vals = keys.map(function(key) {
  42. return scope[key]
  43. })
  44. return Function.apply(null, keys.concat(src)).apply(null, vals)
  45. }
  46. if (arguments.length) line.apply(null, arguments)
  47. return line
  48. }