I saw the following function in the source of a larger web project and was immediately sceptical
$.helperArrayPos = function (array, value) { var i, l = array.length, num = -1; for (i = 0; i < l; i += 1) { if (array[i] === value) { num = i; i = l; } } return num; };
The name of the function tells me that the position of an array is returned. The return num
at the end of the function tells me that the returned value is a number type.
The function signature indicates that an array and a mixed value (probably string) are passed as arguments. This lets me presume, that the mixed value (needle) is looked for in the array (haystack). If the needle is found in the haystack, the position or index is returned, otherwise -1 in the case of needle not being found.
To be sure of what the function does, I wrote some unit tests. The reason for writing unit tests was to be sure of what $.helperArrayPos really does and to see if I couldn’t maybe replace it with jQuery’s $.inArray function, since jQuery was already included. I wrote the tests with QUnit.
test('$.helperArrayPos', function() { var haystack = [ 'banana', 'pear', 'apple', 'cherry', 2, false ]; strictEqual($.helperArrayPos(haystack, 'apple'), 2); strictEqual($.helperArrayPos(haystack, 2), 4); strictEqual($.helperArrayPos(haystack, false), 5); strictEqual($.helperArrayPos(haystack, true), -1); });
The above unit tests confirmed my concern $.helperArrayPos doing the exact same thing as $.inArray. I added further tests to underline my instincts to replace $.helperArrayPos.
strictEqual($.helperArrayPos(haystack, 'apple'), $.inArray('apple', haystack)); strictEqual($.helperArrayPos(haystack, 2), $.inArray(2, haystack)); strictEqual($.helperArrayPos(haystack, false), $.inArray(false, haystack)); strictEqual($.helperArrayPos(haystack, true), $.inArray(true, haystack));
After writing these tests I updated $.helperArrayPos to use $.inArray.
$.helperArrayPos = function (array, value) { return $.inArray(value, array); };
I’m keeping the $.helperArrayPos function to avoid larger refactoring work at this time. I’ve reduced the code size a little keeping things DRY and I’m using a function ($.inArray) that is documented and tested by a reliable 3rd party (thank you jQuery).