“Filtr JavaScript w miejscu Algorytm” Kod odpowiedzi

Filtr JavaScript w miejscu Algorytm

function filterInPlace(a, condition) {
  let i = 0, j = 0;

  while (i < a.length) {
    const val = a[i];
    if (condition(val, i, a)) a[j++] = val;
    i++;
  }

  a.length = j;
  return a;
}
Outrageous Opossum

Filtr JavaScript w miejscu Algorytm

function filterInPlace(a, condition, thisArg) {
  let j = 0;

  a.forEach((e, i) => { 
    if (condition.call(thisArg, e, i, a)) {
      if (i!==j) a[j] = e; 
      j++;
    }
  });

  a.length = j;
  return a;
}

a = [ 1,, 3 ];
document.write('<br>[',a,']');

filterInPlace(a, x=>true);
document.write('<br>[',a,'] compaction when nothing changed');

b = [ 1,,3,,5 ];
document.write('<br>[',b,']');

filterInPlace(b, x=>x!==5);
document.write('<br>[',b,'] with 5 removed');
 Run code snippet
Outrageous Opossum

Odpowiedzi podobne do “Filtr JavaScript w miejscu Algorytm”

Pytania podobne do “Filtr JavaScript w miejscu Algorytm”

Więcej pokrewnych odpowiedzi na “Filtr JavaScript w miejscu Algorytm” w JavaScript

Przeglądaj popularne odpowiedzi na kod według języka

Przeglądaj inne języki kodu