index.js 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. function mker(delimiter) {
  2. function getpath(obj, path) {
  3. path = path || "";
  4. var arr = path.split(delimiter);
  5. var t = obj;
  6. var done = false;
  7. if (arr.length) {
  8. while (arr.length && !done) {
  9. var check = arr.shift();
  10. if (check !== "") {
  11. t = t[check];
  12. }
  13. if (typeof t !== "object") {
  14. done = true;
  15. }
  16. }
  17. }
  18. return t;
  19. }
  20. function setpath(obj, path, value) {
  21. if (typeof obj !== "object" || !obj) {
  22. throw new Error("obj is not Object");
  23. }
  24. if (typeof path !== "string" || path === "") {
  25. throw new Error("path must be string with length > 0");
  26. }
  27. var arr = path.split(delimiter);
  28. var done = false;
  29. var t = obj;
  30. if (arr.length > 1) {
  31. while (arr.length && t && !done) {
  32. var check = arr.shift();
  33. if (typeof t[check] === "object" && arr.length > 0) {
  34. t = t[check];
  35. } else {
  36. done = true;
  37. arr.unshift(check);
  38. }
  39. }
  40. var xt = t;
  41. while (arr.length) {
  42. var tt = arr.shift();
  43. if (arr.length) { //go deeper
  44. if ((parseInt(arr[0]) + "") === ("" + arr[0])) {
  45. xt = xt[tt] = [];
  46. } else {
  47. xt = xt[tt] = {};
  48. }
  49. } else {
  50. //last
  51. xt[tt] = value;
  52. }
  53. }
  54. } else {
  55. if (arr.length === 1 && arr[0] !== "") {
  56. t[arr[0]] = value;
  57. }
  58. }
  59. }
  60. function sort_by_1_col(a, b) {
  61. return a[0] > b[0] ? -1 : a[0] < b[0] ? 1 : 0;
  62. }
  63. function sort_by_1_col_alpha(a, b) {
  64. var x = a[0].toLowerCase(),
  65. y = b[0].toLowerCase();
  66. return x < y ? -1 : x > y ? 1 : 0;
  67. }
  68. function query(obj, str) {
  69. console.log(obj);
  70. console.log(str);
  71. }
  72. function flatten(obj, pre) {
  73. var pre = pre || "";
  74. var r = [];
  75. for (var i in obj) {
  76. if (typeof(obj[i]) === "object") {
  77. r = r.concat(flatten(obj[i], (pre.length > 0 ? pre + delimiter : "") + i));
  78. } else {
  79. r.push([(pre.length > 0 ? pre + delimiter : "") + i, ["boolean", "number"].indexOf(typeof(obj[i])) > -1 ? obj[i] : ("" + obj[i])]);
  80. }
  81. }
  82. r.sort(sort_by_1_col_alpha)
  83. return r;
  84. }
  85. function populate(arr) {
  86. var obj = {}
  87. arr.map(function(a) {
  88. setpath(obj, a[0], a[1]);
  89. })
  90. return obj
  91. }
  92. return {
  93. get: getpath,
  94. set: setpath,
  95. flatten: flatten,
  96. query: query,
  97. populate: populate
  98. }
  99. }
  100. module.exports = mker(".");
  101. module.exports.create = mker;