Fun with JavaScript: count parentheses

Yesterday, I wrote a JavaScript function that returned another function. At one place I wanted to call the returned function immediately, resulting in code looking somewhat like this:

someFunction()()

When seeing that code, I asked myself: would it be possible to count the (pairs of) parentheses? After tinkering a bit, I first came up with (as much whitespace as possible cut away to make it fit into a tweet):

function c(a){function b(){return c(arguments.callee.count)};b.count=1+~~a;return b;}

Then I removed the unnecessary use of arguments.callee:

function c(a){function b(){return c(0-~a)};b.count=0-~a;return b}

Finally I wanted to replace the function name c with something looking like a pair of parentheses, and with the help of Mathias Bynens (@mathias) and Gareth Heyes (@garethheyes) I arrived at this:

function ᑕᑐ(a){function b(){return ᑕᑐ(-~a)};b.count=1-~a;return b}ᑕᑐ.count=1;

After running that code, it is now possible to do (this is from the Firebug console):

>>> ᑕᑐ.count
1
>>> ᑕᑐ()().count
3
>>> ᑕᑐ()()()()().count
6

Yes, I know, ᑕᑐ doesn’t really look like parentheses…

2 thoughts on “Fun with JavaScript: count parentheses

  1. The valid identifier name ‘CD’ kinda-sorta looks like a pair of parenthasis. So does ‘O’.

Comments are closed.