Skip to content

Instantly share code, notes, and snippets.

@kolodny
Last active October 23, 2016 02:15
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 kolodny/ec5ce4489a737f346ceaf029bdad8307 to your computer and use it in GitHub Desktop.
Save kolodny/ec5ce4489a737f346ceaf029bdad8307 to your computer and use it in GitHub Desktop.
Brace closer
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'))
}
const someNumber = 123;
doSomething(
function() {
somethingElse([
function() {
bar({
x: function() {
return 22;
}})}])})
const ok = 'ok';
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