{"size": 1081, "ext": "js", "max_stars_repo_path": "1-projects/archive/global-replace-project-solution/global-replace-project-bonus-solution/global-replace.js", "max_stars_repo_name": "impastasyndrome/Lambda-Resource-Static-Assets", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1-projects/archive/global-replace-project-solution/global-replace-project-bonus-solution/global-replace.js", "max_issues_repo_name": "impastasyndrome/Lambda-Resource-Static-Assets", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1-projects/archive/global-replace-project-solution/global-replace-project-bonus-solution/global-replace.js", "max_forks_repo_name": "impastasyndrome/Lambda-Resource-Static-Assets", "max_forks_repo_forks_event_min_datetime": "2021-11-05T07:48:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T07:48:26.000Z"}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1, "avg_line_length": 22.5208333333, "max_line_length": 75, "alphanum_fraction": 0.5994449584}
const fs = require("fs");

const [TARGET_FILE, OLD_STR, NEW_STR, REPLACE_NUM] = process.argv.slice(2);

fs.readFile(TARGET_FILE, "utf8", (err, data) => {
  if (err) {
    console.log("error reading the file");
    console.log(err);
  }

  let newData;
  if (REPLACE_NUM === undefined) {
    newData = replaceAll(data, OLD_STR, NEW_STR);
  } else {
    newData = replaceSome(data, OLD_STR, NEW_STR, REPLACE_NUM);
  }

  fs.writeFile(TARGET_FILE, newData, "utf8", (err) => {
    if (err) {
      console.log("error writing the file");
      console.log(err);
    } else {
      console.log("write successful");
    }
  });
});

function replaceAll(string, str1, str2) {
  return string.split(str1).join(str2);
}

function replaceSome(string, str1, str2, count) {
  let newString = "";
  let numReplaced = 0;
  let i = 0;
  while (i < string.length) {
    if (string.slice(i, i + str1.length) === str1 && numReplaced < count) {
      newString += str2;
      i += str1.length;
      numReplaced++;
    } else {
      newString += string[i];
      i++;
    }
  }
  return newString;
}
