Advertisement
viligen

objectFactory

May 26th, 2022
551
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function factory(lib, ord){
  2.     const result = []
  3.     for (let order of ord){
  4.         const newObj = Object.assign({}, order['template'])
  5.         let funcs = order['parts']
  6.         for (let f of funcs){
  7.             newObj[f] = lib[f]
  8.         }
  9.         result.push(newObj)
  10.     }
  11.     return result
  12. }
  13.  
  14.  
  15.  
  16. const library = {
  17.     print: function () {
  18.         console.log(`${this.name} is printing a page`);
  19.     },
  20.     scan: function () {
  21.         console.log(`${this.name} is scanning a document`);
  22.     },
  23.     play: function (artist, track) {
  24.         console.log(`${this.name} is playing '${track}' by ${artist}`);
  25.     },
  26. };
  27. const orders = [
  28.     {
  29.         template: { name: "ACME Printer" },
  30.         parts: ["print"],
  31.     },
  32.     {
  33.         template: { name: "Initech Scanner" },
  34.         parts: ["scan"],
  35.     },
  36.     {
  37.         template: { name: "ComTron Copier" },
  38.         parts: ["scan", "print"],
  39.     },
  40.     {
  41.         template: { name: "BoomBox Stereo" },
  42.         parts: ["play"],
  43.     },
  44. ];
  45. const products = factory(library, orders);
  46. console.log(products);
  47.  
Advertisement
RAW Paste Data Copied
Advertisement