_.map – Javascript Problem

This is an exercise taken from the Javascript: From Fundamentals to Functional course by Bianca Gandolfo on FrontEnd Masters.  The characters are taken from a game of Clue – a murder whodunit…

Here I have recreated a map() method in a slightly different way.  Instead of attaching it to the array prototype, I created it as a function which can take in either an array or an object and process it.

On line 3, I test to see if the “list” passed in is an array.  If so, I use a for loop to process the array.  If it is not an array, I assume it is an object and use a for…in loop to process it.  It returns an array of objects called suspectsList in either case.

let temp = [];
const weapons = ["candlestick", "lead pipe", "revolver"];
const objWeapons = {
  weapon1: "candlestick",
  weapon2: "lead pipe",
  weapon3: "revolver"
};

const _ = {
  map(list, func) {
    let temp = [];
    if (Array.isArray(list)) {
      for (let i = 0; i < list.length; i++) {
        temp.push(func(list[i]));
      }
      return temp;
    } else {
      let temp = [];
      for (key in list) {
        temp.push(func(list[key]));
      }
      return temp;
    }
  }
};

const makeBroken = function(item) {
  return `broken ${item}`;
};

console.log("===== From Array List =====");
const output1 = _.map(weapons, makeBroken);
console.log(output1);
// Output
// ===== From Array List =====
// [ 'broken candlestick', 'broken lead pipe', 'broken revolver' ]

console.log("===== From Object List =====");
const output2 = _.map(objWeapons, makeBroken);
console.log(output2);
// Output
// ===== From Object List =====
// [ 'broken candlestick', 'broken lead pipe', 'broken revolver' ]

 

Leave a Reply

Your email address will not be published. Required fields are marked *