Below, you can find another hint for the Challenge.
You should only get here after reading, digesting, and applying the .
It is a bit cumbersome to try the approach suggested in the preceding hint (you need to count carefully). Here is a partial program, which you might have gotten:
It outputs ():
matching the first five lines of the program. But we are not there yet.
Unfortunately, we see another infinite regress around the corner. The more statements we extract from S, the more we need to put in S. We can never catch up.
For extracting the statements from S, we need a program fragment whose length is independent of the number of statements to produce. Compare this to what we had before we worried about newlines:
This program fragment reproduced everything that occurs after the closing quote of the string literal. For instance, we could have added a closing comment in the program, which we could also add to the string literal, and thereby obtain another (longer) program that writes itself as ouput, without changing the statements of the program fragment that writes the tail.
So, we need the program fragment to recognize where to put in newlines without putting that location information in a separate statement for each line. Preferrably, the program fragment recognizes it from the string itself. We could put a special newline marker instead of an actual newline in the string literal. We could use a vertical bar '|' as newline marker (that bar is not used for other purposes):
This gives rise to a new problem: extracting lines from such a string literal with newline markers. The standard function S.substr(i, n) will not be able to do so, since it only extracts a fixed number n of characters starting at index i in S.
However, we could have avoided substr() in our earlier programs, because it can easily be eliminated using charAt(), which extracts a single character from the string (see JavaScript Basics). The program fragment
is equivalent to
This program fragment can easily be adapted to write a newline whenever it encounters a vertical bar ('|').
Can you develop this idea into a better solution?
Try your program in the machine, and see if you can extend it to a complete solution.
It is your turn ...
If you tried this hint, or do not see how it helps, then you are ready for the .