Skip to content

Commit

Permalink
commit changes before shifting directions
Browse files Browse the repository at this point in the history
  • Loading branch information
benatkin committed Apr 7, 2011
1 parent c3f29c7 commit ae7b11f
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 3 deletions.
7 changes: 4 additions & 3 deletions flatten/flatten.js
@@ -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;
};
Expand Down
55 changes: 55 additions & 0 deletions nest/nest.js
@@ -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.