objectToSaneObject.coffee 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. {object} = require 'utila'
  2. module.exports = self =
  3. sanitize: (val) ->
  4. self._toChildren val
  5. _toChildren: (val) ->
  6. if object.isBareObject val
  7. return self._objectToChildren val
  8. else if Array.isArray val
  9. return self._arrayToChildren val
  10. else if val is null or typeof val is 'undefined'
  11. return []
  12. else if typeof val in ['string', 'number']
  13. return [String val]
  14. else
  15. throw Error "not a valid child node: `#{val}"
  16. _objectToChildren: (o) ->
  17. a = []
  18. for own key, val of o
  19. cur = {}
  20. cur[key] = self.sanitize val
  21. a.push cur
  22. a
  23. _arrayToChildren: (a) ->
  24. ret = []
  25. for v in a
  26. ret.push self._toNode v
  27. ret
  28. _toNode: (o) ->
  29. if typeof o in ['string', 'number']
  30. return String o
  31. else if object.isBareObject o
  32. keys = Object.keys(o)
  33. if keys.length isnt 1
  34. throw Error "a node must only have one key as tag name"
  35. key = keys[0]
  36. obj = {}
  37. obj[key] = self._toChildren o[key]
  38. return obj
  39. else
  40. throw Error "not a valid node: `#{o}`"