+-
用于从数组返回项目的函数,其中奇数索引的项目被其前一个偶数索引的数字重复

我在采访某大公司时遇到了这个采访问题。他们要求我编写一个函数next,该函数将数组作为输入值并返回下一个可用数字。

[偶数索引中的数字表示奇数索引处数组中的下一个数字。例如,[2,2,1,7,3,5]表示我们有两个2,一个7和3个5。因此,调用next()将一次依次输出22755 5。当没有可用数字时,在这种情况下,当返回第三个5时,该函数将引发异常。

所以这个问题很开放。他们没有明确指定我应如何实现此功能。唯一的要求是实现上述行为,即一次输出下一个可用的数字。

在采访中,我认为将此函数放在Array的原型链上是有意义的,因此我们可以直接在这样的数组上调用此函数

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 

我注意到人们在说把功能作为Array原型的一部分是个坏主意。所以这是另一种解决方案

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++];
}

但是问题是,它不记得上一个输出,而是继续下一个输出。它将始终输出数组中的第一项。

我一直以为也许我们可以将此next实现为迭代器,但我自己无法实现。

有人可以帮我吗?

1
投票
这是我的解决方案。如果您有任何问题,请告诉我:

const generatorFunc = function* (arr) { let i = 0; while (i < arr.length) { yield arr[i]; i++; } }; const buildIterator = (arr) => { const generatedArr = arr.reduce((acc, item, itemIndex) => { const isEven = itemIndex % 2 === 0; if (isEven) { const value = arr[itemIndex + 1]; const iterationCount = item; return acc.concat(Array(iterationCount).fill(value)); }; return acc; }, []); const generator = generatorFunc(generatedArr); return { next: () => generator.next().value }; }; const myIterator = buildIterator([2,2,1,7,3,5]);

1
投票

const array = [2, 2, 1, 7, 3, 5]; function sequencer(arr) { const actualArray = [] let currentIndex = 0; for (let i = 0; i < arr.length; i++) { if (i % 2 === 0) { x = i; } else { actualArray.push(...new Array(arr[x]).fill(arr[i])); } } return function() { if (currentIndex >= actualArray.length) throw new Error("execced array length") return actualArray[currentIndex++]; } } let arrSequencer = sequencer(array); for (let i = 0; i < 7; i++) { console.log(arrSequencer()); }