Pages

Tuesday, September 20, 2016

pow (Java or JavaScript?)

In A Powerful Trick we encountered the following code snippet that could be used to implement a function called pow:

    if (exponent < 0)
        return 1 / pow(number, -1 * exponent);
    else if (exponent == 0)
        return 1;
    else // exponent > 0
        return number * pow(number, exponent - 1); 

Is this Java or JavaScript code? In fact, it could be either!

A definition of pow in JavaScript, which a) declares the function pow in terms of its parameters; b) defines a particular implementation of the function; and c) attempts to conform to the Google JavaScript Style Guide, might look like this:

    function pow(number, exponent) {
      if (exponent < 0) {
        return 1 / pow(number, -1 * exponent);
      }
      else if (exponent == 0) {
        return 1;
      }
      else { // exponent > 0
        return number * pow(number, exponent - 1);
      }
    }

Similarly, here's a definition of pow in Java, which a) includes the same implementation; b) declares the method pow in terms of its parameters, the types of its two parameters (int in both cases), and the type of its return value (double); c) declares the method to be a public static method; and d) attempts to conform to the Google Java Style Guide:

    public static double pow(int number, int exponent) {
      if (exponent < 0) {
        return 1 / pow(number, -1 * exponent);
      }
      else if (exponent == 0) {
        return 1;
      }
      else { // exponent > 0
        return number * pow(number, exponent - 1);
      }
    }