Comment by Someone

11 years ago

In JavaScript, the API could be fairly complex. Thing is, JavaScript doesn't have arrays of numbers. So, what should the function do if the array passed in contains a null, an undefined, a string such as "7", "012", "008", or "2+3", a function, another array, a hash, etc?

I can easily see this grow into a function accepting options indicating such things as "null values are zeroes", "ignore null values", "evaluate string arguments", etc, or maybe into a factory that produces customized averaging functions.

For example, average([null,1,2,3],[4,5]) could either be 3 (the average of all numbers), 2.5 (sum of numbers divided by number of 'root' items), undefined (input format error), 3.25 (average of average of [1,2,3] and average of [4,5]), etc.

And what if it gets passed arrays of equal size? "average([1,2,3],[7,4,5])" could easily be interpreted as a vector average, and produce [4,3,4]

Silly? Yes, but if you want to write a robust library in JavaScript, you have to think about what to do with all these kinds of input.

And of course, there are the simple variants of harmonic mean, arithmetic mean, and geometric mean, and several others (https://en.m.wikipedia.org/wiki/Average)

...and this example is none of those things, and untouched in 2 years.

If an interviewee did respond with some or all of the points you raise he'd have turned a potential negative into a positive point. This instance is the simple arithmetic mean with no consideration of anything.

I stand by my original comment. Nine times out of ten an average is going to be resolutely unexceptional, one time in ten or less it's the core of a well-crafted solution with a decent reason for being.

IMO the behavior of "average" should be unspecified if it's passed anything but a single nonempty array of numbers. Making it even a tiny bit more robust is wasted work. Moreover, it's harmful because it encourages sloppy calling code.

  • The committee that designed SQL had a different opinion.

    • Right, that's a different philosophy. You can use JS as a dynamic language with DWIM qualities, like SQL. But I prefer to write JS code as if it were a typed language without nulls, and use tools to enforce that. I think that approach will win.