Search code examples
whitespaceindentationabstract-syntax-treecode-formattingconcrete-syntax-tree

Is it humanly possible to fix indent size issues w/o access to a syntax tree?


Asked another way, if I showed you this masked code file, using only your human brain, is it possible to fix the indentation issues, even if you know it should be 2-space indentation?

  xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
   xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
     xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    x
x

   xxxxxxxxxxxxxxxxxxxxxxxxxxx

I have my own ideas, but I don't want to bias the answer. The actual source code and language will be revealed after I get a good batch of answers. Feel free to post your fix as a code block below.

This test assumes the following:

  1. You have no idea the language in which this code is written.
  2. All you know is how many spaces or tabs lead up to the first character of each line. In this case, there are no tabs (just spaces).
  3. You know what the indent size should be. In this case, 2 spaces.

Note: If it's possible with your human brain, it should also be possible with code, right?

Bonus Points (optional): How would you break-down the logic to tackle this problem?

EDIT: Here's the source code, from which these exes were created:

function greet(firstName, lastName) {

    var firstName = prompt('What is your first name?');
    var lastName = prompt('Last name?');

    var fullName = firstName + ' ' + lastName;
    for (var i = 0; i < 10; i++) {
        console.log('Hello,', fullName + '!');
    }
}

greet(firstName, lastName);

Solution

  •  xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    
        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
           xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    
                xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                     xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
                    x
                x
    
        xxxxxxxxxxxxxxxxxxxxxxxxxxx