7
Your challenge today is to refactor JavaScript code. You will take three strings as input; a JavaScript string, a old variable name, and the name you want to refactor it to. For example, an input of
"var x = 100; alert(x);", "x", "num"
Will output
"var num = 100; alert(num);"
Here's a more advanced test case:
"var gb = 1; var g = bg = 2; gb = bg = g = function(gg) { alert(gb); };
var str = 'g gb bg gg'; var regexp = /gb gb gb/g; //comment gb gb g g
/*gb gb g g*/", "gb", "aaa"
It should output
var aaa = 1; var g = bg = 2; aaa = bg = g = function(gg) { alert(aaa); };
var str = 'g gb bg gg'; var regexp = /gb gb g g/g; //comment gb gb g g
/*gb gb g g*/
And the same JS input with the other arguments "g", "aaa"
should output
var gb = 1; var aaa = bg = 2; gb = bg = aaa = function(gg) { alert(gb); };
var str = 'g gb bg gg'; var regexp = /gb gb gb/g; //comment gb gb g g
/*gb gb g g*/
Here is one last much more complicated test case:
var g = 1; "g\"g"; "g'"; g; '"g\'g"g'; /g"\/*\//g; g; "// /*"; g; "*/"
It should output, with other parameters "g"
and "a"
, this:
var a = 1; "g\"g"; "g'"; a; '"g\'g"g'; /g"\/*\//g; a; "// /*"; a; "*/"
(sidenote: I really like /g"\/*\//g
; I think that's just evil :D
)
Full specification:
- For simplicity, you may ignore scope. Ex.
"var a=1; function(){var a=2;}; var o={a: 3}", "a", "b"
can outputvar b=1; function(){var b=2;}; var o={b: 3}
. - Text in strings (
'...' and "..."
), regexps and their modifiers (/.../...
), and comments (//...\n
and/*...*/
) must not be modified. - Also for simplicity, a valid identifier is one that starts with a letter, dollar sign, or underscore, and the rest of the characters are letters, numbers, dollar signs, or underscores.
- You may assume that the input contains no syntax errors.
- This is code-golf, so the shortest code in bytes will win.
- If you use network access, all bytes downloaded from the network count towards your score.
- You must use an actual programming language. No IDE solutions, like emacs or vim keystrokes. ;)
3wait, what's wrong with vim keystrokes? :-) – John Dvorak – 2014-02-05T06:34:44.833
do we have to support
/[/]/
(character classes containing unescaped slash characters)? Ruby doesn't. – John Dvorak – 2014-02-05T08:46:00.627Asking the same as @JanDvorak above: do we need to support /[/]/ (character classes containing unescaped slash characters)? Most languages with built-in support for regular expressions don't; however, JavaScript does. – Toothbrush – 2014-02-17T10:56:00.693
@toothbrush No, you do not. (Sorry for forgetting to reply ;-)) – Doorknob – 2014-02-17T14:12:57.293