Jordan Eldredge

Code golfing interview questions

Several years ago (a decade?) I was chatting with a work colleague about code golfing and we had the idea to try to golf some of the interview questions we used at work. One of the questions was to flatten a deeply nested list. I came up with this very funny JavaScript answer, of which I am still proud:

var flatten=l=>eval(`[${l}]`)

This “works” because JavaScript will implicitly cast the array to a string, and JavaScript’s way of serializing an array is to make it a comma separated list without any brackets. Thus, nested lists just become a flat list:

String([10, [20, 30, [40]]])
// => '10,20,30,40'

And eval then rehydrates the string back into a real Array of values.