javascriptecmascript-6es5-shim

Javascript ES6 to ES5 conversion


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?


Solution

  • There are the following ES5 incompatibilities in your code:

    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);