I'd prefer one of the easy-to-understand versions above, but if you really want to avoid changing the length of the array for optimization purposes, I suppose you could replace the last item similar to you're originally doing instead.
const linearSearchSentinel = (array, itemToFind) => {
const { length } = array;
const lastItem = array[length - 1];
array[length - 1] = itemToFind;
let i = 0;
while (array[i] !== itemToFind) i++;
array[length - 1] = lastItem;
console.log(
(i !== length - 1 || lastItem === itemToFind)
? 'FOUND ON INDEX ' + i
: 'NOT FOUND'
);
};
linearSearchSentinel(['foo', 'bar', 'baz'], 'foo');
linearSearchSentinel(['foo', 'bar', 'baz'], 'baz');
linearSearchSentinel(['foo', 'bar', 'baz'], 'nope');
This is all for informational purposes only, of course - if you were actually facing a practical problem where you needed to find the index of an element in an array in JavaScript for a , it would make more sense to use the built-in indexOf
method, which would be far faster and easier.