Zorgatone
4/6/2016 - 8:21 AM

Iterable Objects

Iterable Objects

function iterize(obj, type) {
  obj[Symbol.iterator] = function() {
    let keyit = Object.keys(obj)[Symbol.iterator]();

    return {next() {
      let {done, value} = keyit.next();

      if (done) {
        return {done};
      } else if(type && type === "array") {
        return {done, value: [
          value,
          obj[value]
        ]};
      } else if(type && type === "object") {
        return {done, value: {
          key: value, value: obj[value]
        }};
      }

      return {done, value: obj[value]};
    }};
  };

  return obj;
}
Object.prototype[Symbol.iterator] = function() {
  let obj = this;
  let keyit = Object.keys(obj)[Symbol.iterator]();

  return {next() {
    let {done, value} = keyit.next();

    if (done) {
      return {done};
    }

    return {done, value: {
      key: value, value: obj[value]
    }};
  }};
};