vendredi 13 janvier 2023

JavaScript: Command Patterns [duplicate]

I have trouble in understanding a specific line of the command design pattern, the code goes here:

const carManager = {
  // request information
  requestInfo(model, id) {
    console.log(`The information for ${model} with ID ${id} is hahahaha`);
  },
  // purchase the car
  buyVehicle(model, id) {
    console.log(`You have successfully purchased Item ${id}, a ${model}`);
  },
  // arrange a viewing
  arrangeViewing(model, id) {
    console.log(
      `You have successfully booked a viewing of ${model} ( ${id} ) `
    );
  },
};

carManager.execute = function (name) {
  return (
    carManager[name] &&
    carManager[name].apply(carManager, [].slice.call(arguments, 1))
  );
};

carManager.execute("arrangeViewing", "Ferrari", "14523");
carManager.execute("requestInfo", "Ford Mondeo", "54323");
carManager.execute("requestInfo", "Ford Escort", "34232");
carManager.execute("buyVehicle", "Ford Escort", "34232");

What is the carManager[name] && carManager[name].apply(carManager, [].slice.call(arguments, 1)) doing exactly? Also I have understanding of call, bind and apply methods separately and I understand that a command pattern takes away the responsibility of issuing commands from anything that's executing commands, delegating the responsibilities to different objects. Thus car manager and execute are separate, I just don't get the dry run of that complex line.

Aucun commentaire:

Enregistrer un commentaire