Permalink
Browse files

Another take at pre-compilation, which doesn't use eval.

  • Loading branch information...
1 parent 7373c09 commit 1c373d59aa4ffea4f5a20a67a70c37900cedb051 @hildjj committed Jan 22, 2013
Showing with 30 additions and 38 deletions.
  1. +30 −38 jsonpointer.js
View
@@ -1,28 +1,12 @@
var console = require("console");
var untilde = function(str) {
- return str.replace(/(~.)|[\b\f\n\r\t\v\\']/g, function(m) {
+ return str.replace(/~./g, function(m) {
switch (m) {
case "~0":
return "~";
case "~1":
return "/";
- case "'":
- return "\\'";
- case "\b":
- return "\\b";
- case "\f":
- return "\\f";
- case "\n":
- return "\\n";
- case "\r":
- return "\\r";
- case "\t":
- return "\\t";
- case "\v":
- return "\\v";
- case "\\":
- return "\\\\";
}
throw("Invalid tilde escape: " + m);
});
@@ -43,30 +27,38 @@ var compile = function(pointer) {
}
}
- var fn = "";
- var part;
- var len = pointer.length - 1;
- if (len < 0) {
- fn += "if (typeof value !== 'undefined') { throw(new Error('Invalid JSON pointer for set.')); }\n";
- } else {
- for (var i=0; i<len; i++) {
- part = untilde(pointer[i]);
- fn += "if (!obj) { return null; }\n";
- fn += "obj = obj['" + part + "'];\n"
+ var len = pointer.length;
+ if (len === 0) {
+ return function(obj, value) {
+ if (typeof value !== 'undefined') {
+ throw(new Error('Invalid JSON pointer for set.'));
+ }
+ return obj;
}
- part = untilde(pointer[len]);
- fn += "if (!obj) { return null; }\n";
- fn += "if (typeof value !== 'undefined') {\n" +
- " var old_value = obj['" + part + "'];\n" +
- " obj['" + part + "'] = value;\n" +
- " obj = old_value;\n" +
- "} else {\n" +
- " obj = obj['" + part + "'];\n" +
- "}\n";
}
- fn += "return obj;\n"
- return new Function("obj", "value", fn);
+ pointer = pointer.map(untilde);
+
+ return function(obj, value) {
+ var parent = null;
+ var part = null;
+ for (var i=0; i<len; i++) {
+ if (!obj) {
+ if (typeof value !== 'undefined') {
+ throw new Error("Path not found for set");
+ }
+ return null;
+ }
+ parent = obj;
+ part = pointer[i];
+ obj = obj[part];
+ }
+
+ if (typeof value !== 'undefined') {
+ parent[part] = value;
+ }
+ return obj;
+ }
}
var get = function(obj, pointer) {

0 comments on commit 1c373d5

Please sign in to comment.