I got this interview question when interviewing with some big company. They asked me to write out a function next
, which takes an array as the input value and returns the next available number.
The number at even index in the array indicates the number of the next number in the array at the odd index
. For example, [2,2,1,7,3,5]
meaning that we have two 2
s, one 7
and 3 5
s. So calling next()
will output 2
2
7
5
5
5
sequentially one at a time. And when there is no available number, in this case when the third 5
is returned, the function would throw exception.
So this question was quite open ended. They didn't explicitly specify how I should implement this function. The only requirement was to achieve the behavior mentioned above, i.e. output next available number one at time.
During the interview I thought it would make sense to put this function on the prototype chain of Array
so we can call this function directly on an array like this
const array = [2, 2, 1, 7, 3, 5];
Array.prototype.next = function() {
const buffer = [];
let x;
let index = 0;
for (let i = 0; i < this.length; i++) {
if (i % 2 === 0) {
x = i;
} else {
buffer.push(...new Array(this[x]).fill(this[i]));
}
}
return buffer[index++];
};
console.log(array.next()); // 2
console.log(array.next()); // 2
console.log(array.next()); // 2
I noticed that people are saying it's bad idea to make the function part of the Array
prototype. So here is another solution
function getNext(array) {
const buffer = [];
let x;
let index = 0;
for (let i = 0; i < array.length; i++) {
if (i % 2 === 0) {
x = i;
} else {
buffer.push(...new Array(array[x]).fill(array[i]));
}
}
return buffer[index++];
}
However the problem is, it doesn't remember the last output and move on to the next one. It will always output the first item in the array.
I always thought maybe we can implement this next
as an iterator but I couldn't implement it myself.
Can anyone help me with it?