objectToSaneObject.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Generated by CoffeeScript 1.12.7
  2. var object, self,
  3. hasProp = {}.hasOwnProperty;
  4. object = require('utila').object;
  5. module.exports = self = {
  6. sanitize: function(val) {
  7. return self._toChildren(val);
  8. },
  9. _toChildren: function(val) {
  10. var ref;
  11. if (object.isBareObject(val)) {
  12. return self._objectToChildren(val);
  13. } else if (Array.isArray(val)) {
  14. return self._arrayToChildren(val);
  15. } else if (val === null || typeof val === 'undefined') {
  16. return [];
  17. } else if ((ref = typeof val) === 'string' || ref === 'number') {
  18. return [String(val)];
  19. } else {
  20. throw Error("not a valid child node: `" + val);
  21. }
  22. },
  23. _objectToChildren: function(o) {
  24. var a, cur, key, val;
  25. a = [];
  26. for (key in o) {
  27. if (!hasProp.call(o, key)) continue;
  28. val = o[key];
  29. cur = {};
  30. cur[key] = self.sanitize(val);
  31. a.push(cur);
  32. }
  33. return a;
  34. },
  35. _arrayToChildren: function(a) {
  36. var i, len, ret, v;
  37. ret = [];
  38. for (i = 0, len = a.length; i < len; i++) {
  39. v = a[i];
  40. ret.push(self._toNode(v));
  41. }
  42. return ret;
  43. },
  44. _toNode: function(o) {
  45. var key, keys, obj, ref;
  46. if ((ref = typeof o) === 'string' || ref === 'number') {
  47. return String(o);
  48. } else if (object.isBareObject(o)) {
  49. keys = Object.keys(o);
  50. if (keys.length !== 1) {
  51. throw Error("a node must only have one key as tag name");
  52. }
  53. key = keys[0];
  54. obj = {};
  55. obj[key] = self._toChildren(o[key]);
  56. return obj;
  57. } else {
  58. throw Error("not a valid node: `" + o + "`");
  59. }
  60. }
  61. };