Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of set in ES6 to ES5

I have a set over which I am iterating in ES6. I am trying to convert it to its equivalent in ES5. My build is getting failed because of ES6. That's why I am converting it to ES5.

Here's my code in ES6

service.getDevices = function (date) {
        var result = [];
        var deviceList = devices[date.getTime()];

        for (let item of deviceList) { // browser compatibility: support for ECMA6
            result.push({"deviceName": item});
        }

        return result;
    }

I am getting error because of 'let'. I tried using for (var item in deviceList), it does not display the charts.

I also tried this:

for(var i = 0; i < deviceList.length(); i++){
           result.push({"deviceName" : deviceList[i]});
       }

Even this is not working for set. can someone help and tell me how to iterate over a set in ES5 and if that is not possible, is there any equivalent way of doing it?

like image 893
chan Avatar asked Dec 10 '22 09:12

chan


2 Answers

Why not just iterate through the data and map the result with Array#map.

result = deviceList.map(function (item) {
    return { deviceName: item };
});
like image 53
Nina Scholz Avatar answered Dec 21 '22 17:12

Nina Scholz


This is a basic set es5 class that I have used variations on over the years.

function Set(items) {
  this._data = {};
  this.addItems(items);
}

Set.prototype.addItem = function(value) {
  this._data[value] = true;
  return this;
}

Set.prototype.removeItem = function(value) {
  delete this._data[value];
  return this;
}

Set.prototype.addItems = function(values) {
  for (var i = 0; i < values.length; i++) {
    this.addItem(values[i]);
  }
  return this;
}

Set.prototype.removeItems = function(values) {
  for (var i = 0; i < values.length; i++) {
    this.removeItem(values[i]);
  }
  return this;
}

Set.prototype.contains = function(value) {
  return !!this._data[value];
}

Set.prototype.reset = function() {
  this._data = {};
  return this;
}

Set.prototype.data = function() {
  return Object.keys(this._data);
}

Set.prototype.each = function(callback) {
  var data = this.data();
  for (var i = 0; i < data.length; i++) {
    callback(data[i]);
  }
}

var set = new Set(['a', 'b', 'c']);
console.log(set.addItems(['a', 'd', 'e']).removeItems(['b', 'e']).data());
console.log(set.contains('a'));
console.log(set.contains('e'));

set.each(console.log)
like image 35
Amos47 Avatar answered Dec 21 '22 15:12

Amos47