0

I have this function here that returns a function. The job it does is that it receives two or more arguments and it saves them in an object. If the number of arguments is equal to one then we find all the words in the string that match the stored keys in that object and replace them with their values. I have managed to do it but I want to achieve this in a single go. At this moment the keys are being replaced with values one by one because I am using a for loop to iterate. Is there a better way to do it so that we can replace all keys in one go?

function censor() {
  let newObj = {};
  return function(...args) {
    if (args.length > 1) {
      newObj[args[0]] = args[1];
      return newObj;
    } else {
      for (let key in newObj) {
        console.log(args[0] = args[0].replace(args[0].match(key), newObj[key]));
      };
    }
  }
}

const changeScene = censor();
console.log(changeScene('dogs', 'cats'));
console.log(changeScene('quick', 'slow'));
changeScene('The quick, brown fox jumps over the lazy dogs.');
Ali Mustafa
  • 588
  • 1
  • 9

0 Answers0