-2

I have this ES6 code:

var occupationJson = {
  "Occupation": [{
      "value": "Engineer",
      "startDate": "2016-01-01",
      "endDate": "2016-01-31"
    },
    {
      "value": "Manager",
      "startDate": "2016-02-01",
      "endDate": "2016-02-28"
    },
    {
      "value": "Director",
      "startDate": "2016-03-05",
      "endDate": "2016-03-25"
    },
    {
      "value": "CEO",
      "startDate": "2016-04-04",
      "endDate": "2016-04-30"
    },
    {
      "value": "Board Member",
      "startDate": "2016-05-02",
      "endDate": "2099-05-31"
    }
  ]
};

var tenureJson = {
  "Tenure": [{
      "value": "Full Time",
      "startDate": "2016-01-01",
      "endDate": "2016-01-31"
    },
    {
      "value": "Part Time",
      "startDate": "2016-02-04",
      "endDate": "2016-02-28"
    },
    {
      "value": "Casual",
      "startDate": "2016-04-01",
      "endDate": "2016-04-25"
    },
    {
      "value": "Full Time",
      "startDate": "2016-05-01",
      "endDate": "2016-07-01"
    }
  ]
};

var dates = [];

// Loop through Occupation and Tenure arrays to get start and end dates
occupationJson.Occupation.forEach(function(item) {
  dates.push(item.startDate);
  dates.push(item.endDate);
});

tenureJson.Tenure.forEach(function(item) {
  dates.push(item.startDate);
  dates.push(item.endDate);
});

// Sort the dates in ascending order
dates.sort(function(a, b) {
  return new Date(a) - new Date(b);
});

const occupationStartDateArray = occupationJson.Occupation.map(item => item.startDate);
const occupationEndDateArray = occupationJson.Occupation.map(item => item.endDate);

const tenureStartDateArray = tenureJson.Tenure.map(item => item.startDate);
const tenureEndDateArray = tenureJson.Tenure.map(item => item.endDate);

// Combine the start date arrays and sort them in ascending order
const allStartDateArray = [...occupationStartDateArray, ...tenureStartDateArray].sort();

// Combine the end date arrays and sort them in ascending order
const allEndDateArray = [...occupationEndDateArray, ...tenureEndDateArray].sort();

const allDatesArray = [...allStartDateArray, ...allEndDateArray];
const sortedAllDatesArray = allDatesArray.sort();
const uniqueDatesArray = [...new Set(sortedAllDatesArray)];
console.log(uniqueDatesArray);
var shortestDate = uniqueDatesArray[0];


const result = {
  "data": []
};

// Assign the shortest date to a new start date variable
let newStartDate = shortestDate;

// Loop through the unique dates and find the next shortest date
for (let i = 1; i < uniqueDatesArray.length; i++) {
  const nextShortestDate = uniqueDatesArray[i];
  let newEndDate = "";
  // Check if the next shortest date is from the all start date array
  if (allStartDateArray.includes(nextShortestDate) && nextShortestDate > newStartDate) {
    // Subtract a day from the next shortest date and assign it to the end date
    const endDate = new Date(nextShortestDate);
    endDate.setDate(endDate.getDate() - 1);
    newEndDate = endDate.toISOString().substring(0, 10);

    // Do something with the new start and end dates, such as logging them
    console.log(`New start date: ${newStartDate}`);
    console.log(`New end date: ${newEndDate}`);
    if (newEndDate) {
      const occupation = occupationJson.Occupation.find(function(item) {
        return newStartDate >= item.startDate && newEndDate <= item.endDate;
      });

      const tenure = tenureJson.Tenure.find(function(item) {
        return newStartDate >= item.startDate && newEndDate <= item.endDate;
      });

      const dataItem = {
        "startDate": newStartDate,
        "endDate": newEndDate,
        "Occupation": occupation ? occupation.value : "",
        "Tenure": tenure ? tenure.value : ""
      };

      if (dataItem.Occupation == "" && dataItem.Tenure == "") {

      } else {
        result.data.push(dataItem);
      }

    }


    // Assign the next shortest date to the new start date
    const startDate = new Date(newEndDate);
    startDate.setDate(startDate.getDate() + 1);
    newStartDate = startDate.toISOString().substring(0, 10);
  } else if (nextShortestDate > newStartDate) {
    // Assign the next shortest date to the end date
    newEndDate = nextShortestDate;




    // Do something with the new start and end dates, such as logging them
    console.log(`New start date: ${newStartDate}`);
    console.log(`New end date: ${newEndDate}`);
    if (newEndDate) {
      const occupation = occupationJson.Occupation.find(function(item) {
        return newStartDate >= item.startDate && newEndDate <= item.endDate;
      });

      const tenure = tenureJson.Tenure.find(function(item) {
        return newStartDate >= item.startDate && newEndDate <= item.endDate;
      });

      const dataItem = {
        "startDate": newStartDate,
        "endDate": newEndDate,
        "Occupation": occupation ? occupation.value : "",
        "Tenure": tenure ? tenure.value : ""
      };

      if (dataItem.Occupation == "" && dataItem.Tenure == "") {

      } else {
        result.data.push(dataItem);
      }
    }

    const startDate = new Date(newEndDate);
    startDate.setDate(startDate.getDate() + 1);
    newStartDate = startDate.toISOString().substring(0, 10);
  }

}

console.log(result);

When I run this code in Browser I get the array with 10 items and which is correct. However I need to run this in a older system which only supports ES5 scripts. I tried to convert this into ES5 using freeze object and windows property to false but it is not working. Issue is I am using too many const in my script and ES5 does not support const and I am not sure how to fix the issue. Any help is greatly appreciated.

I tried to use babel to convert the code, but it did not work.

I tried to use object freeze and Document property set to false, but that did not work either.

What can I do to port the script for running on a ES5 supported system?

trincot
  • 317,000
  • 35
  • 244
  • 286
  • So what is the version you tried to convert it too? – epascarello May 03 '23 at 11:58
  • What did babel spit out that did not work? – epascarello May 03 '23 at 11:59
  • Hi @epascarello Thanks for the quick response. I am new to Babel, And somehow it's giving me the same code. There's no preset to select for ES2015. I tried force transform but the code that I get is the same as original. I apologies if this sounds dumb but I am new to this and could not find much to achieve – Lakshay Verma May 03 '23 at 12:14
  • I am getting below error post conversion. Set" is not defined in at line number 107 – Lakshay Verma May 03 '23 at 13:03
  • *"There's no preset to select for ES2015."*: why would you want to do that? ES6=ES2015, which is what you already have, but you want ES5. ES5 is **not** ES2015. – trincot May 03 '23 at 14:27
  • 1
    Hi @trincot Thanks for the answer, it worked for me like a charm. And apologies for ES2015, I was going through so many articles and messed in explaining it. What I wanted is ES5 and the code that you explained is quiet descriptive and help me understand it quiet well. Once again thank you for the answer. – Lakshay Verma May 03 '23 at 15:28

1 Answers1

0

There are the following ES5 incompatibilities in your code:

  • Arrow functions: use standard function instead
  • Template literals: use string concatenation instead
  • Set: use a specific Array#filter solution instead
  • const, and let: use var instead
  • Array spread syntax: use Array#concat instead
  • Array#includes: use Array#indexOf instead
  • Array#find: use Array#filter instead

Note that you don't need to use Object.freeze to try to mimic const: That keyword is only there to protect the program from doing unintended assignments. In practice you can just replace those with var -- but check that the scope is still fine for the program to run correctly (this is the case in your code).

For replacing the use of Set (in order to remove duplicates), I used the fact that the array was already sorted, so then you just have to filter out values that have the same value following it.

Here is the code when I made the above replacements:

var occupationJson = {
  "Occupation": [
    {
      "value": "Engineer",
      "startDate": "2016-01-01",
      "endDate": "2016-01-31"
    },
    {
      "value": "Manager",
      "startDate": "2016-02-01",
      "endDate": "2016-02-28"
    },
    {
      "value": "Director",
      "startDate": "2016-03-05",
      "endDate": "2016-03-25"
    },
    {
      "value": "CEO",
      "startDate": "2016-04-04",
      "endDate": "2016-04-30"
    },
    {
      "value": "Board Member",
      "startDate": "2016-05-02",
      "endDate": "2099-05-31"
    }
  ]
};

var tenureJson = {
  "Tenure": [
    {
      "value": "Full Time",
      "startDate": "2016-01-01",
      "endDate": "2016-01-31"
    },
    {
      "value": "Part Time",
      "startDate": "2016-02-04",
      "endDate": "2016-02-28"
    },
    {
      "value": "Casual",
      "startDate": "2016-04-01",
      "endDate": "2016-04-25"
    },
    {
      "value": "Full Time",
      "startDate": "2016-05-01",
      "endDate": "2016-07-01"
    }
  ]
};

var dates = [];

// Loop through Occupation and Tenure arrays to get start and end dates
occupationJson.Occupation.forEach(function(item) {
  dates.push(item.startDate);
  dates.push(item.endDate);
});

tenureJson.Tenure.forEach(function(item) {
  dates.push(item.startDate);
  dates.push(item.endDate);
});

// Sort the dates in ascending order
dates.sort(function(a, b) {
  return new Date(a) - new Date(b);
});

var occupationStartDateArray = occupationJson.Occupation.map(function (item) { return item.startDate });
var occupationEndDateArray = occupationJson.Occupation.map(function (item) { return item.endDate});

var tenureStartDateArray = tenureJson.Tenure.map(function (item) { return item.startDate});
var tenureEndDateArray = tenureJson.Tenure.map(function (item) { return item.endDate});

// Combine the start date arrays and sort them in ascending order
var allStartDateArray = occupationStartDateArray.concat(tenureStartDateArray).sort();

// Combine the end date arrays and sort them in ascending order
var allEndDateArray = occupationEndDateArray.concat(tenureEndDateArray).sort();

var allDatesArray = allStartDateArray.concat(allEndDateArray);
var sortedAllDatesArray = allDatesArray.sort();

var uniqueDatesArray = sortedAllDatesArray.filter(function (dt, i) { return dt !== sortedAllDatesArray[i+1]});
console.log(uniqueDatesArray);
var shortestDate = uniqueDatesArray[0];


var result = {
  "data": []
};

// Assign the shortest date to a new start date variable
var newStartDate = shortestDate;

// Loop through the unique dates and find the next shortest date
for (var i = 1; i < uniqueDatesArray.length; i++) {
  var nextShortestDate = uniqueDatesArray[i];
  var newEndDate="";
  // Check if the next shortest date is from the all start date array
  if (allStartDateArray.indexOf(nextShortestDate) > -1 &&  nextShortestDate>newStartDate) {
    // Subtract a day from the next shortest date and assign it to the end date
    var endDate = new Date(nextShortestDate);
    endDate.setDate(endDate.getDate() - 1);
    newEndDate = endDate.toISOString().substring(0, 10);

    // Do something with the new start and end dates, such as logging them
    console.log("New start date: " + newStartDate);
    console.log("New end date: " + newEndDate);
    if (newEndDate) {
      var occupation = occupationJson.Occupation.filter(function(item) {
        return newStartDate >= item.startDate && newEndDate <= item.endDate;
      })[0];

      var tenure = tenureJson.Tenure.filter(function(item) {
        return newStartDate >= item.startDate && newEndDate <= item.endDate;
      })[0];

      var dataItem = {
        "startDate": newStartDate,
        "endDate": newEndDate,
        "Occupation": occupation ? occupation.value : "",
        "Tenure": tenure ? tenure.value : ""
      };

      if (dataItem.Occupation == "" && dataItem.Tenure == "") {
      } else {
        result.data.push(dataItem);
      }
    }

   
    // Assign the next shortest date to the new start date
    var startDate=new Date(newEndDate);
    startDate.setDate(startDate.getDate()+1);
    newStartDate =startDate.toISOString().substring(0,10);
  } else if(nextShortestDate>newStartDate){
    // Assign the next shortest date to the end date
    newEndDate = nextShortestDate;
    // Replace template strings with old-style string concatenation
    console.log("New start date: " + newStartDate);
    console.log("New end date: " + newEndDate);
    if (newEndDate) {
      var occupation = occupationJson.Occupation.filter(function(item) {
        return newStartDate >= item.startDate && newEndDate <= item.endDate;
      })[0];
      var tenure = tenureJson.Tenure.filter(function(item) {
        return newStartDate >= item.startDate && newEndDate <= item.endDate;
      })[0];

      var dataItem = {
        "startDate": newStartDate,
        "endDate": newEndDate,
        "Occupation": occupation ? occupation.value : "",
        "Tenure": tenure ? tenure.value : ""
      };

      if (dataItem.Occupation == "" && dataItem.Tenure == "") {
      } else {
        result.data.push(dataItem);
      }
    }
    
    var startDate = new Date(newEndDate);
    startDate.setDate(startDate.getDate()+1);
    newStartDate = startDate.toISOString().substring(0,10);
  }
}

console.log(result);
trincot
  • 317,000
  • 35
  • 244
  • 286