r/programming • • Aug 10 '12

Write any javascript code with just these characters: ()[]{}+!

http://patriciopalladino.com/blog/2012/08/09/non-alphanumeric-javascript.html
1.3k Upvotes

288 comments sorted by

View all comments

-4

u/deletecode Aug 10 '12

Replacing !![] -> 1 makes this a lot shorter :). (I know !![] is actually "true")

To start our journey to the world of brackets, lets represent the numbers with our new alphabet.

0 is easily obtained by casting an empty array like this +[]. In a similar way, we can cast the empty array to boolean to get true, and then to 1 with +1. Those numbers, along with + would be enough to get every natural.

But if we take advantage of JavaScript coercion of types, we can reduce the size of the sequence of the numbers in two ways.

First, if we add a number and a boolean, both operands would be casted to numbers. So instead of using sums of ones to generate larger values, we can add just a 1 and a sequence of trues (we can use more than one true at a time beacuse addition is left-to-right assosiative). For instance, here is 4: !+[]+1+1+1.

The second idea is to get strings representing large numbers and cast them in order to get a shorter sequence of symbols. Once we obtained all the possible digits like we did above with 4, we can get the desired string by adding the first digit to [] (to make it a character), and combinig all of them with + (with the necessary parens). Once again, the left-to-right assosiativite would save us lots of chars. Finally, we only need to cast that. Doing this, 12 would look like this: +((+1+[])+(!+[]+1)).

The second idea is to reuse what we’ve done above in order to get a shorter sequence of symbols. The main purpose of doing this is to represent bigger numbers without the need to sum 1 each time to get to our number, so instead we get it’s string representation and cast it to number. For example, representing 12 adding ones would be: (!+[]+1+1+1+1+1+1+1+1+1+1+1), but by resuing 1 and 2 we can be represen it like this: +((+1+[])+(!+[]+1)). Here, we have casted the first digit to string, added the second, and then, converted everything to a number. Speaking in terms of code, on the first case we did a simple sum: (1+1+1+1+1+1+1+1+1+1+1+1); and on the second one we concatenated two strings and casted them into a number like this: +("1"+2).

Having said that, here is a table of all the possible digits:

0 +[]

1 +1

2 !+[]+1

3 !+[]+1+1

4 !+[]+1+1+1

5 !+[]+1+1+1+1

6 !+[]+1+1+1+1+1

7 !+[]+1+1+1+1+1+1

8 !+[]+1+1+1+1+1+1+1

9 !+[]+1+1+1+1+1+1+1+1

6

u/mattaereal Aug 10 '12

That's cool! :), but you're forgetting the main purpose, not to have alphanumeric stuff in our encoding ;). And you're also adding a char to the charset ;(

1

u/deletecode Aug 10 '12

Yeah, I guess I defeated the point of a nearly pointless exercise :)