Last active
October 23, 2016 02:15
-
-
Save kolodny/ec5ce4489a737f346ceaf029bdad8307 to your computer and use it in GitHub Desktop.
Brace closer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = closer; | |
function closer(codeString) { | |
var lines = codeString.split('\n'); | |
var lastIndent = 0; | |
var currentScope = { indent: 0, children: [] }; | |
for (lineIndex = 0; lineIndex < lines.length; lineIndex++) { | |
var line = lines[lineIndex]; | |
var currentIndent = /^\s*/.exec(line)[0].length; | |
if (/^\s*√\s*$/.test(line)) { | |
var scope = currentScope; | |
var out = []; | |
while (scope && scope.indent > currentIndent) { | |
out = out.concat(scope.openers.split('').reverse().map(c => ({ | |
'{': '}', | |
'(': ')', | |
'[': ']' | |
})[c])); | |
scope = scope.parent; | |
} | |
lines[lineIndex] = ' '.repeat(currentIndent) + out.join('') | |
} else { | |
if (currentIndent > lastIndent) { | |
currentScope = { parent: currentScope, indent: currentIndent, children: [] } | |
currentScope.parent.children.push(currentScope); | |
currentScope.openers = /[[{(]*$/.exec(lines[lineIndex - 1])[0]; | |
} else { | |
currentScope = currentScope.parent | |
} | |
} | |
} | |
console.log(lines.join('\n')) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const someNumber = 123; | |
doSomething( | |
function() { | |
somethingElse([ | |
function() { | |
bar({ | |
x: function() { | |
return 22; | |
}})}])}) | |
const ok = 'ok'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var closer = require('./'); | |
var testString = function() {/* | |
const someNumber = 123; | |
doSomething( | |
function() { | |
somethingElse([ | |
function() { | |
bar({ | |
x: function() { | |
return 22; | |
√ | |
const ok = 'ok'; | |
*/}.toString().split('\n').slice(1, -1).join('\n'); | |
closer(testString) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment