Skip to content

Instantly share code, notes, and snippets.

@dvv
Created May 4, 2010 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dvv/389768 to your computer and use it in GitHub Desktop.
Save dvv/389768 to your computer and use it in GitHub Desktop.
exports.convertors = {
"number" : function(x){
var n = +x;
return (!isNaN(n)) ? n : x;
},
"date" : function(x){
var date = x + "0000-01-01T00:00:00Z".substring(x.length);
date.replace(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/, function(dummy, y, mp1, d, h, m, s){
x = new Date(Date.UTC(+y, +mp1 - 1, +d, +h, +m, +s));
});
return x;
},
/*"array" : function(x){
// TODO: arrays should be enclosed with braces!
if (x.indexOf(',') > -1) {
var array = [];
string.split(',').forEach(function(i){
array.push(stringToValue(i)); // TODO: , parameters));
});
return array;
}
},*/
"re" : function(x){
// poorman regexp? *foo, bar*
/***v = (v.charAt(0) != '*') ? '^' + v : v.substring(1);
v = (v.slice(-1) != '*') ? v + '$' : v.substring(0, v.length-1);***/
return new RegExp(x, 'i');
},
"RE" : function(x){return new RegExp(x)},
"boolean": function(x){return Boolean(x)},
"string" : function(x){return x},
};
function stringToValue(string, parameters){
function tryConvertor(type, value){
value = (value instanceof Array) ? value[0] : value;
var t = exports.convertors[type]; // TODO: how to disallow possible access intrinsic object props here!
if (t)
return (t instanceof Function) ? t(value) : t;
else
throw new URIError("Unknown type " + type); // TODO: should we throw or just ignore?
}
// TODO: arrays should be enclosed with braces!
if (string.indexOf(',') > -1) {
var array = [];
string.split(',').forEach(function(x){
array.push(stringToValue(x)); // TODO: , parameters));
});
return array;
}
// try process explicit modifier
if(string.indexOf(":") > -1){
var parts = string.split(":");
return tryConvertor(parts.shift(), decodeURIComponent(parts));
}
// substitute positional parameter, if any
if(string.charAt(0) == "$"){
return parameters[parseInt(string.substring(1)) - 1];
}
// decode the string
string = decodeURIComponent(string);
// guess datatype, iterating by convertors
switch(string){
case "true": return true;
case "false": return false;
case "null": return null;
case "undefined": return undefined;
}
for (var t = ["number","date"], l = t.length, i = 0; i < l; ++i) {
var v = tryConvertor(t[i], string);
if (!(typeof v === 'string'))
return v;
}
//
if(exports.jsonQueryCompatible){
if(string.charAt(0) == "'" && string.charAt(string.length-1) == "'"){
return JSON.parse('"' + string.substring(1,string.length-1) + '"');
}
}
return string;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment