DEV Community

Bruce Axtens
Bruce Axtens

Posted on

Google Closure Compiler ... for C programmers

Yes, you read it right, C programmers.

I've been having a fun time at Exercism, as my last posting indicates. Today, I worked on a C challenge, which required the writing of a function to say whether a number was an Armstrong Number (also known as a Narcissistic Number) or not.

What I wrote works ok, but I got to wondering, as I do, what the Closure Compiler would make of the code, seeing as JavaScript is in C's family tree.

So I followed my own custom link to Google Closure Compiler and got to work.

The first thing I needed to do was make the C more JavaScript-like. I achieved this by replacing the int declarations with var in the body and replacing the function header's int with function. The parameter's int was removed completely.

So this

int numlen(int n) {
    int len = 0;
    int div = n, mod = div % 10;
    while (mod != 0) {
        len++;
        div = div / 10;
        mod = div % 10;
    }
    return len;
}
Enter fullscreen mode Exit fullscreen mode

becomes this

function numlen(n) {
    var len = 0;
    var div = n, mod = div % 10;
    while (mod != 0) {
        len++;
        div = div / 10;
        mod = div % 10;
    }
    return len;
}
Enter fullscreen mode Exit fullscreen mode

Closure Compiler boils that down to

function numlen(a) {
  for (var b = 0, c = a % 10; 0 != c;) {
    b++, a /= 10, c = a % 10;
  }
  return b;
}
Enter fullscreen mode Exit fullscreen mode

which I then took back into C, finally ending up with

int numlen(int n) {
  int div = n;
  int len = 0; 
  for (int mod = div % 10; 0 != mod;) {
    len++;
    div /= 10;
    mod = div % 10;
  }
  return len;
}
Enter fullscreen mode Exit fullscreen mode

Is there a speed improvement? I don't know. Is there a readability improvement? Probably not. In fact, I pity the maintenance programmer who might not catch the fact the that for has no iteration clause, only an initialisation and a termination.

That's not the full solution, by the way, but just enough to give the gist of what I'm using Closure Compiler for. When my mentor gives the thumbs up to my code, I expect the full solution will appear on my public profile.

In a subsequent post I may show how I used Closure Compiler to help with a C# exercism.

Top comments (0)