This information could be useful to beginner and intermediate programmers so I decided to share it with you.
Scenario:
Sometimes with more complex problems it is useful to switch from coding directly in the browser IDE to running the code locally.
One of the best reasons of doing so is arguably the ability to debug your program, which is of course not possible on server side run code.
When I say debug your code I mean not simply printing out statements and figuring out what is wrong but using breakpoints and inspecting the states on a step by step basis.
We are going to use javascript in this example for simplicity but this should be possible in any language. Some requiring more initial effort than others, depending on whether or not you get generators out of the box, but it’s of course possible however not too trivial to roll your own.
So as a first step we’ve just slapped a copypasta of our code in the browser IDE between two tags in a local file and saved it, then loaded the file in the browser.
Problem:
The first problem is the function “print”, but this is easily solved by aliasing it to console.log, as well as printErr:
const print = console.log.bind(console);
const printErr = print;
Now the real “problem” is that readline() function.
We could just replace each readline() call with hardcoded strings, which is what I’ve been doing initially.
But I got tired of this quickly and there is of course a better way:
Generators.
Explaining generator functions is out of the scope of this tutorial and there already exists enough information to be found in the webs.
In a nutshell they can halt at arbitrary points after "yield"ing a value and return that value to the caller as normal functions would, but they persist after returning that value and keep track of the internal state and context and where the execution halted so they can carry on when they are called the next time. If that sounds a bit like an iterator to you then thumbs up! Generators are iterators that iterate over values which can be generated on the fly.
Solution
Cutting to the chase, here is the required code to emulate readline (Example input from the Hidden word puzzle)
function* __readline(){
let lines = `2
BAC
BOB
3 3
BAC
BOB
RED`.split(/\n\s*/)
while(lines.length) yield lines.shift()
}
const _readline = __readline();
function readline(){
return _readline.next().value
}
Now on the first readline call, 2 is returned, then BAC, then BOB, then 3 3, and so on until there is no line left in the array.
The nice thing about this is that now all we need to do for new tests is to update the lines variable with a new block of lines or array, which can easily be extracted for copy+paste from the browser IDE with a few lines of code and also once finished the whole thing can be used 1:1 minus the monkey patching stuff and it will work without requiring any post-editing.
Let me know if that was useful, you spot any typos or you have any other comments, cheers.