Not only was my nondeterministic turing machine implementationway too long at 20 lines, it was also wrong. Shortly after @dionyziz reported a bug and it took me until last night to get around to fixing it.

Image by Henry Work via Flickr

The problem was that when I was passing tapes for each possible step into the next iteration of the algorithm the good old “everything is a reference” javascript feature bit me in the arse. Because of this all the tapes looked exactly like the tape belonging to the last state inspected and so when you moved the instructions around a bit you could make my implementation fail without actually changing the actual turing machine.

Fixing it was a simple matter of strategically using underscore’s clone function to make sure ever inspected state is acting on its own version of the tape.

And since the fix was so simple and I didn’t feel like studying the subject that has been the bane of my existence for the past two years, I decided to try codegolfing the algorithm a bit. Doing so I accidentally came upon what is possibly javascript’s funnest feature.

```var δ=function(S,s,e){var π=_.keys,Θ={},k,i,λ,μ,ι,Σ=_.size,β,ψ; if(π(s).indexOf(e)>=0)return!0 for(k in s){i=s[k][0],λ=s[k][1],ψ=S[k][λ[i]]||S[k].B;for(ι=0;ψ,ι<Σ(ψ);){ μ=ψ[ι++],β=_.clone(λ),β.splice(i,1,μ.w),Θ[μ.n]=[i+μ.m,β]}}return Σ(Θ)?δ(S,Θ,e):!!0};```

Glorious 252 characters of nondeterministic turing machine right there! I’d say 252 bytes, but it’s not, look at all those shiny unicode characters!

Turns out even though javascript legally only allows numbers, letters and the \$ and _ signs for variable names … using almost any imaginable unicode character is also legal. Perhaps slightly difficult to type, but definitely a useful feature for making more expressive code.

Especially when codegolfing or implementing physics or maths.

Not sure I’ll ever be using this again though … oh and here’s a slightly more readable version:

```var δ = function(S,s,e){ var π=_.keys,Θ={},k,i,λ,μ,ι,Σ=_.size,β,ψ; if(π(s).indexOf(e)>=0) return!0 for(k in s){ i=s[k][0], λ=s[k][1], ψ=S[k][λ[i]]||S[k].B;   for(ι=0; ψ,ι<Σ(ψ); ){ μ=ψ[ι++]; β=_.clone(λ); β.splice(i,1,μ.w); Θ[μ.n]=[i+μ.m,β]; } } return Σ(Θ)?δ(S,Θ,e):!!0; };```

Before you ask, machine instructions look like this and you can find a script for running all of this over at my github.

#### Learned something new? Want to become a better engineer? 💌

Join 9,400+ people just like you already improving their skills.

Here's how it works 👇

Leave your email and I'll send you an Interactive Modern JavaScript Cheatsheet 📖 right away. After that you'll get a thoughtfully written email every week about React, JavaScript,  and lessons learned in my 20 years of writing code for companies ranging from tiny startups to Fortune5 behemoths.

Man, I love your way of writing these newsletters. Often very relatable and funny perspectives about the mundane struggles of a dev. Lightens up my day. ~ Kostas