Sobes.tech
Middle+

const customMap = (array, transform) => { // niečo ako array.map(transform); }; const stringResults = customMap([1, 2, 3], item => item.toString()); const lengths = customMap(["ahoj", "svet"], item => item.length);

sobes.tech AI

Odpoveď od AI

Funkcia customMap by mala akceptovať pole a funkciu transformácie, a vrátiť nové pole, kde každý prvok je výsledkom aplikácie funkcie na zodpovedajúci prvok pôvodného poľa. Toto je analógie k Array.prototype.map.

Príklad implementácie:

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]

Tu manuálne prechádzame pole, aplikujeme funkciu transform na každý prvok a zbierame výsledky do nového poľa.