JSFiddle - React, Tailwind, and code Playground
by Jaume Vinyes
JavaScript
const source = [1,2,3,3,3,4,4,4,4,5,6,]
const target = 4
const firstAndLast = (source, target) => {
let begin = -1
let end = -1
const mid = (source.length / 2) - 1
if (source[mid] < target) {
return firstAndLast(source.slice(-mid), target)
}
if (source[mid] > target) {
return firstAndLast(source.slice(0, mid), target)
}
console.log(mid)
begin= mid
end = mid
let i = 1
while(source[mid - i] === target) {
console.log("begin", begin)
console.log(source[mid - i])
begin--;
i++
}
while(source[mid + i] === target) {
end++;
i++
}
return[begin, end]
}
console.log(firstAndLast(source, target))