Skip to content

Instantly share code, notes, and snippets.

@rtoal
Created March 12, 2017 01:34
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 rtoal/e6dde567574c25e57dbe4afbfa77ce45 to your computer and use it in GitHub Desktop.
Save rtoal/e6dde567574c25e57dbe4afbfa77ce45 to your computer and use it in GitHub Desktop.
An illustration of preprocessing lines of text for later use of the offside rule
const program = `
def f(x):
y = 0
while x < y:
if p:
x = 3
else:
for x in range(10):
print(x)
print(2)
def g(y):
return 3
f(10)
f(11)
`;
function findIndentsAndDedents(text, emit) {
const stack = [0];
for (let line of text.split('\n')) {
if (line.trim() === '') continue;
const indent = /^( *)/.exec(line)[1].length;
if (indent === stack[stack.length - 1]) {
emit(line.substring(indent));
} else if (indent > stack[stack.length - 1]) {
stack.push(indent);
emit('\u21b3' + line.substring(indent));
} else {
for (let dedents = 1; true; dedents++) {
const next = (stack.pop(), stack[stack.length-1]);
if (indent > next) {
return 'Indent Error';
} else if (indent === next) {
emit('\u21b5'.repeat(dedents) + line.substring(indent));
break;
}
}
}
}
return true;
}
findIndentsAndDedents(program, line => console.log(line));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment