Permalink
Browse files

commit changes before shifting directions

  • Loading branch information...
1 parent c3f29c7 commit ae7b11f2ecfb05db1b03ffb9d802231d307f5ede @benatkin committed Apr 7, 2011
Showing with 59 additions and 3 deletions.
  1. +4 −3 flatten/flatten.js
  2. +55 −0 nest/nest.js
View
@@ -1,9 +1,10 @@
exports.flatten = function(obj) {
- var flattened = {};
+ var flattened = {},
+ escapeExpr = /([\\\/])/g;
var join = function(path, key) {
- if (key.indexOf && key.indexOf("/") != -1) {
- key = key.replace("/", "\\/");
+ if (escapeExpr.test(key)) {
+ key = key.replace(escapeExpr, "\\$1");
}
return ((path === "") ? "" : path + "/") + key;
};
View
@@ -0,0 +1,55 @@
+exports.nest = function(obj) {
+ var nested = {}, // the result
+ highest = {}, // the highest number, if all items at a path are numbers
+ path, // the path string
+ keys, // the path array, split on /
+ key, // the current key
+ keyPath, // the path of the current key
+ hasEscaped = /\\/,
+ splitExpr = /^\/|(?:^(\\\\)+)\/|(?:[^\\])\/|(?:[^\\](\\\\)+)\//,
+ unescapeExpr = /\\([\\\/])/g,
+ pos, match, rest, i;
+
+ for (path in obj) {
+ if (obj.hasOwnProperty(path)) {
+ if (hasEscaped.test(path)) {
+ keys = [];
+ rest = path;
+ for (i=0; i < 1000; i++) {
+ pos = rest.find(splitExpr);
+ if (pos == -1) {
+ keys.push(rest);
+ break;
+ } else {
+ match = rest.match(splitExpr);
+ keys.push(keys.substring());
+ }
+ }
+ } else {
+ keys = keys.split("/");
+ }
+
+ nobj = nested, npath = "";
+ for (i=0; i < path.length - 1; i++) {
+ nkey = path[i];
+ if (typeof nobj[key] !== "object") {
+ if (/\d+/.test(object)) {
+ nobj[nkey] = [];
+ } else {
+ nobj[nkey] = {};
+ }
+ }
+ if (toString.call(obj[nkey]) === '[object Array]') {
+ if (/\d+/.test(object)) {
+ nkey = parseInt(nkey);
+ if (! (highest[npath] && highest[npath] > nkey)) {
+ highest[npath] = nkey;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // convert any sparse arrays to objects
+};

0 comments on commit ae7b11f

Please sign in to comment.