Home > OS >  How does the test method works on this example of EloquentJavascript book?
How does the test method works on this example of EloquentJavascript book?

Time:03-13

On the 4th line it uses the 2nd parameter of the function called map. But there is nothing about what actually transform(element) do. Maybe I'm missing something or its referencing another function. This example is on the 5th chapter of EloquentJavaScript book third edition.

function map(array, transform) {
  let mapped = [];
  for (let element of array) {
    mapped.push(transform(element));
  }
  return mapped;
}

let rtlScripts = SCRIPTS.filter(s => s.direction == "rtl");
console.log(map(rtlScripts, s => s.name));
// → ["Adlam", "Arabic", "Imperial Aramaic", …]

CodePudding user response:

transform is a function that's passed into the map function as an argument. For each filtered object of the array the transform is called, and the name value of that object is returned, and that is pushed into an array (which is returned from map once the iteration is complete).

The arrow function syntax can be a little confusing so here is the same code using a function declaration. Note: at this point you're not calling it - you're passing it in as a reference so it can be called later (in map).

// Pass in the array of filtered objects, and the callback function
// which returns the name value of the obj in the current loop iteration
const out = map(rtlScripts, function (obj) {
  return obj.name;
});

In this example I've replaced "element" with "obj" to make it easier to understand what data structures are being manipulated.

function map(array, transform) {
  let mapped = [];

  // For each object in the array call the
  // transform function which returns only the name value
  // and add that to the array
  for (let obj of array) {
    mapped.push(transform(obj));
  }
  return mapped;
}

const SCRIPTS = [{name: 'English',direction:'ltr'},{name:'Adlam',direction:'rtl'},{name: 'French',direction:'ltr'},{name:'Arabic',direction:'rtl'},{name:'Imperial Aramaic',direction:'rtl'}];

// `filter` out all the objects that are "rtl"
const rtlScripts = SCRIPTS.filter(obj => obj.direction == "rtl");

// Pass in the filtered array of objects, and for
// each of them call the function which returns only the name
const out = map(rtlScripts, function (obj) {
  return obj.name;
});

console.log(out);

// → ["Adlam", "Arabic", "Imperial Aramaic", …]

  • Related