re: Typical JavaScript interview exercises (explained) VIEW POST

FULL DISCUSSION
 
const heroes = [
  { name: 'Wolverine',      family: 'Marvel',    isEvil: false },
  { name: 'Deadpool',       family: 'Marvel',    isEvil: false },
  { name: 'Magneto',        family: 'Marvel',    isEvil: true  },
  { name: 'Charles Xavier', family: 'Marvel',    isEvil: false },
  { name: 'Batman',         family: 'DC Comics', isEvil: false },
  { name: 'Harley Quinn',   family: 'DC Comics', isEvil: true  },
  { name: 'Legolas',        family: 'Tolkien',   isEvil: false },
  { name: 'Gandalf',        family: 'Tolkien',   isEvil: false },
  { name: 'Saruman',        family: 'Tolkien',   isEvil: true  }
];

function copyObject(obj, cb) {
  let callbackPassed = false,
      stringToObj = null,
      objToString = null;

  if (cb && typeof cb !== "function") throw new Error("Second Argument must be function.");
  else callbackPassed = true;

  objToString = JSON.stringify(obj);
  stringToObj = JSON.parse(objToString);

  if (callbackPassed) cb(stringToObj);

  return stringToObj;
}


const newHeroes = heroes.map(h => {
  return copyObject(h, function (obj) {
    obj.name = obj.name.toUpperCase();
  });
});
// you can copy Objects with JSON :)
// Object.assign is better solution for this kind of problems.

code of conduct - report abuse