Javascript function for finding local extrema