Solution to level 40 in Untrusted: http://alex.nisnevich.com/untrusted/