123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125 |
- function mker(delimiter) {
- function getpath(obj, path) {
- path = path || "";
- var arr = path.split(delimiter);
- var t = obj;
- var done = false;
- if (arr.length) {
- while (arr.length && !done) {
- var check = arr.shift();
- if (check !== "") {
- t = t[check];
- }
- if (typeof t !== "object") {
- done = true;
- }
- }
- }
- return t;
- }
- function setpath(obj, path, value) {
- if (typeof obj !== "object" || !obj) {
- throw new Error("obj is not Object");
- }
- if (typeof path !== "string" || path === "") {
- throw new Error("path must be string with length > 0");
- }
- var arr = path.split(delimiter);
- var done = false;
- var t = obj;
- if (arr.length > 1) {
- while (arr.length && t && !done) {
- var check = arr.shift();
- if (typeof t[check] === "object" && arr.length > 0) {
- t = t[check];
- } else {
- done = true;
- arr.unshift(check);
- }
- }
- var xt = t;
- while (arr.length) {
- var tt = arr.shift();
- if (arr.length) { //go deeper
- if ((parseInt(arr[0]) + "") === ("" + arr[0])) {
- xt = xt[tt] = [];
- } else {
- xt = xt[tt] = {};
- }
- } else {
- //last
- xt[tt] = value;
- }
- }
- } else {
- if (arr.length === 1 && arr[0] !== "") {
- t[arr[0]] = value;
- }
- }
- }
- function sort_by_1_col(a, b) {
- return a[0] > b[0] ? -1 : a[0] < b[0] ? 1 : 0;
- }
- function sort_by_1_col_alpha(a, b) {
- var x = a[0].toLowerCase(),
- y = b[0].toLowerCase();
- return x < y ? -1 : x > y ? 1 : 0;
- }
- function query(obj, str) {
- console.log(obj);
- console.log(str);
- }
- function flatten(obj, pre) {
- var pre = pre || "";
- var r = [];
- for (var i in obj) {
- if (typeof(obj[i]) === "object") {
- r = r.concat(flatten(obj[i], (pre.length > 0 ? pre + delimiter : "") + i));
- } else {
- r.push([(pre.length > 0 ? pre + delimiter : "") + i, ["boolean", "number"].indexOf(typeof(obj[i])) > -1 ? obj[i] : ("" + obj[i])]);
- }
- }
- r.sort(sort_by_1_col_alpha)
- return r;
- }
- function populate(arr) {
- var obj = {}
- arr.map(function(a) {
- setpath(obj, a[0], a[1]);
- })
- return obj
- }
- return {
- get: getpath,
- set: setpath,
- flatten: flatten,
- query: query,
- populate: populate
- }
- }
- module.exports = mker(".");
- module.exports.create = mker;
|