Skip to content

Instantly share code, notes, and snippets.

@williammalo
Forked from 140bytes/LICENSE.txt
Last active October 5, 2015 19:07
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 williammalo/2859590 to your computer and use it in GitHub Desktop.
Save williammalo/2859590 to your computer and use it in GitHub Desktop.
blockifyIndents

Turns indentation into {curly brackets} Great for a yml to json converter or something. Credit to @maettig for writing all* the code.

Turn this:

if(3==3)
    alert("obviously!")
    alert("lol!")

Into:

if(3==3){
    alert("obviously!")
    alert("lol!")
}

jsperf showing the different methods:

http://jsperf.com/blockifyindents

*almost

function(a,b,c){
for(
b=1; //loop starts at 1
(c=RegExp('(\n\t{'+b+++'}).*(\\1.*)*','g')) //for every indent level (b)
.test(a=a.replace(c,'{$&}')); //put curly braces around blocks
); //if regex test returns false, end loop
return a //return the blockified string
}
function(a,b,c){for(b=1;(c=RegExp('(\n\t{'+b+++'}).*(\\1.*)*','g')).test(a=a.replace(c,'{$&}')););return a}
//shorter version (Only if indents are smaller than 9!!!)
function(a,b){for(b=9;--b;)a=a.replace(RegExp('(\n\t{'+b+'}).*(\\1.*)*','g'),'{$&}');return a}
{
"name": "blockifyIndents",
"description": "Turns indentation into {curly brackets}.",
"keywords": [
"indentation",
"tabs",
"block",
"whitespace",
"yml"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div id = code>
if(3==3)
alert("obviously!")
alert("lol!")
</div>
<script>
blockifyIndents = function(a,b,c){for(b=1;(c=RegExp('(\n\t{'+b+++'}).*(\\1.*)*','g')).test(a=a.replace(c,'{$&}')););return a}
document.write(blockifyIndents(document.getElementById("code").innerHTML))
</script>
@maettig
Copy link

maettig commented Jun 6, 2012

You can either replace 9 with 99 (which is very slow, see this jsPerf test case) or use something like the following to make it work with all indention levels.

function(a,b,c){for(b=1;(c=RegExp('(\n\t{'+b+++'}).*(\\1.*)*','g')).test(a);)a=a.replace(c,'{$&}');return a}

@williammalo
Copy link
Author

@maettig
Sweet! I'll test it a bit and I'll probably make it the official version.
I also added safari and chrome to the jsperf.

@williammalo
Copy link
Author

@maettig
Congratulations! Your version (edited to remove 1 byte) is now the official function!
Thanks a bunch!

@maettig
Copy link

maettig commented Jun 6, 2012

This is a funny hack. You are executing test() and replace() in reverse order. But it works. It's even faster. I wonder why.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment