Skip to content

Instantly share code, notes, and snippets.

@DavidWells
Created October 2, 2015 18:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidWells/50b891a9e012a1e748c2 to your computer and use it in GitHub Desktop.
Save DavidWells/50b891a9e012a1e748c2 to your computer and use it in GitHub Desktop.
/*jslint browser: true, vars: true, white: true, maxerr: 50, indent: 4 */
(function (console)
{
"use strict";
function transform(string)
{
var questionMark = string.indexOf("?");
var colon = string.indexOf(":", questionMark);
if (questionMark === -1 || colon === -1)
{
return string;
}
var condition = string.substring(0, questionMark);
var expressions = string.substring(questionMark + 1, string.length);
var trueExpression = null;
var falseExpression = null;
console.log("expressions: " + expressions);
// While looking in pairs, find the location where the colon occurs before the question mark.
questionMark = expressions.indexOf("?");
colon = expressions.indexOf(":");
while ((questionMark !== -1 && colon !== -1) && (questionMark < colon))
{
questionMark = expressions.indexOf("?", questionMark + 1);
colon = expressions.indexOf(":", colon + 1);
}
console.log("\t" + "questionMark: " + questionMark);
console.log("\t" + "colon: " + colon);
trueExpression = expressions.substring(0, colon);
falseExpression = expressions.substring(colon + 1, expressions.length);
console.log("condition: " + condition);
console.log("trueExpression: " + trueExpression);
console.log("falseExpression: " + falseExpression);
console.log("-");
return ("if (" + condition + ") {\n" + transform(trueExpression) + "\n} else {\n" + transform(falseExpression) + "\n}");
}
function unittest()
{
console.log(transform("(i < 0 ? function1() : function2())"));
console.log("---");
console.log(transform("i < 0 ? function1() : function2()"));
console.log("---");
console.log(transform("i < 0 ? function1() : i === 0 ? function2() : function3()"));
console.log("---");
console.log(transform("i > 0 ? i === 1 ? function1() : function2() : function3()"));
console.log("---");
console.log(transform("i > 0 ? i === 1 ? function1() : i === 2 ? function2() : function3() : function4()"));
console.log("---");
console.log(transform("i > 0 ? i === 1 ? function1() : i === 2 ? function2() : function3() : i === 0 ? function4() : function5()"));
console.log("---");
console.log(transform("f&&!f.error?k.button.b==k.button.c.G?k.button.Q(b,e,f,c,d):k.button.b==k.button.c.o&&k.button.P(b,e,f,c,d):(console.error(f),f=f.error.message||chrome.i18n.getMessage(\"error_tooltip\"),k.button.v(b.id,f),d({action:\"error\"}))"));
}
unittest();
}(window.console));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment