Array.prototype.slice() mutuje orginalną tablicę

0

Witam,

Mam problemy z funkcja splice()

function removeItem(array, n) {
  // return a new array without the item on position 'n', effectively removing it from the array

  return array.splice(n, 1);

To rozwiazanie oblewa test:

describe.only('removeItem', () => {
  it('returns a new array without the item in the passed position', () => {
    expect(removeItem([1], 0)).toEqual([]);
    expect(removeItem([1, 2, 3], 1)).toEqual([1, 3]);
    expect(removeItem([1, 7, 0, 4], 2)).toEqual([1, 7, 4]);
    expect(removeItem([1, 2, 1], 2)).toEqual([1, 2]);
  });
  it("doesn't mutate the passed array, i.e. it returns a new array, leaving the original one unmodified", () => {
    const original = [1, 2, 3];
    const modified = removeItem(original, 1);
    expect(original).not.toEqual(modified);
    expect(original).toEqual([1, 2, 3]);
  });
  it('ignores arguments out of the length of the array', () => {
    expect(removeItem([1, 2, 3], 8)).toEqual([1, 2, 3]);
  });
});
2

zobacz sobie, co zwraca funkcja splice, bo masz jakieś dziwne założenia, co ona robi: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

1

popraw na:

function removeItem(array, n) {
  array.splice(n, 1);
  return array;
}
3
Robert Karpiński napisał(a):

popraw na:

function removeItem(array, n) {
  array.splice(n, 1);
  return array;
}

ale wymóg jest w testach, że ma nie mutować oryginalnej tablicy, więc prędzej:

function removeItem(array, n) {
  const copy = array.slice();
  copy.splice(n, 1);
  return copy;
}
3

Można jeszcze tak:

function removeItem(array, n) {
  return array.filter((_, i) => i !== n);
}

1 użytkowników online, w tym zalogowanych: 0, gości: 1