Sobes.tech
Middle+

const customMap = (array, transform) => { // něco jako array.map(transform); }; const stringResults = customMap([1, 2, 3], item => item.toString()); const lengths = customMap(["ahoj", "svět"], item => item.length);

sobes.tech AI

Odpověď od AI

Funkce customMap by měla přijímat pole a funkci transformace a vracet nové pole, kde každý prvek je výsledkem aplikace funkce na odpovídající prvek původního pole. To je analogické k Array.prototype.map.

Příklad implementace:

const customMap = (array, transform) => {
  const result = [];
  for (let i = 0; i < array.length; i++) {
    result.push(transform(array[i], i, array));
  }
  return result;
};

const stringResults = customMap([1, 2, 3], item => item.toString());
console.log(stringResults); // ["1", "2", "3"]

const lengths = customMap(["hello", "world"], item => item.length);
console.log(lengths); // [5, 5]

Zde manuálně procházíme pole, aplikujeme funkci transform na každý prvek a shromažďujeme výsledky do nového pole.