This answers the Problem of the Week from May 8, 2012. The identity of this well-known computer science function is the binary search. The following is the same code from before with the variables more properly named:


var binarySearch = (function(internal) {
  function search(array, item, temp1, temp2) {
    array = array[temp1 = parseInt((temp2 = array.length) / 2)] == item
      ? temp1
      : temp1 > 0 && array[temp1] > item
        ? +search.call(internal, array.slice(0, temp1), item)
        : temp1 < temp2 - 1 && array[temp1] < item
          ? temp1 + 1 + search.call(internal, array.slice(temp1 + 1), item)
          : internal;
    return this !== internal && isNaN(array) ? -1 : array;
  }
  return search;
})({});

To tell you the truth, after using the real names in the function definition, I realized that the code could be shortened a little more without changing the execution by doing the following:


var binarySearch = (function(internal) {
  return function(array, item, temp1, temp2) {
    array = array[temp1 = parseInt((temp2 = array.length) / 2)] == item
      ? temp1
      : temp1 > 0 && array[temp1] > item
        ? +binarySearch.call(internal, array.slice(0, temp1), item)
        : temp1 < temp2 - 1 && array[temp1] < item
          ? temp1 + 1 + binarySearch.call(internal, array.slice(temp1 + 1), item)
          : internal;
    return this !== internal && isNaN(array) ? -1 : array;
  };
})({});

1 Comment

POW – Unnamed Function #2 | Chris West's Blog · August 16, 2012 at 1:21 PM

[…] this Problem of the Week will be posted a week from today on Wednesday, August 15, 2012 was posted here. This entry was posted in Blog, JavaScript, JScript, Problem of the Week and tagged Array, […]

Leave a Reply

Your email address will not be published. Required fields are marked *