1.0.1 • Published 5 years ago

class-loop v1.0.1

Weekly downloads
3
License
MIT
Repository
github
Last release
5 years ago

Class-Loop

Creates an Iterator for the class, to use in for-of loop

Problem

In Javascript, for-of loop cannot be used in object.

Eg:

class TestClass {
  constructor() {
    this.property0 = 'prop0';
    this.property1 = 'prop1';
  }
}
// Create an instance
const instance = new TestClass();

for (let i of instance) {
  properties.push(i);
}

// Above will throw 'TypeError: instance is not iterable' error

Using 'Class-Loop' module

  • TypeScript

import ClassLoop class.

import { ClassLoop } from 'class-loop';

Using with a class

import { ClassLoop } from 'class-loop';

class TestClass extends ClassLoop {
  property0: string;
  property1: string;
  constructor() {
    super();
    this.property0 = 'prop0';
    this.property1 = 'prop1';
  }
}

const instance = new TestClass();

const properties = [];
for (const i of instance) {
  properties.push(i);
}

console.log(properties);
/* Output
[
  { key: 'property0', value: 'prop0' },
  { key: 'property1', value: 'prop1' }
]
*/
  • Javascript
const { ClassLoop } = require('class-loop');

Using with a class

const { ClassLoop } = require('class-loop');
class TestClass extends ClassLoop {
  constructor() {
    super();
    this.property0 = 'prop0';
    this.property1 = 'prop1';
  }
}

const instance = new TestClass();

const properties = [];
for (let i of instance) {
  properties.push(i);
}

console.log(properties);

/* Output
[
  { key: 'property0', value: 'prop0' },
  { key: 'property1', value: 'prop1' }
]
*/

Override loop function in child class.

  • TypeScript
import { ClassLoop } from 'class-loop';

class TestClass extends ClassLoop {
  property0: string;
  property1: string;
  constructor() {
    super();
    this.property0 = 'prop0';
    this.property1 = 'prop1';
  }

  // Write your own loop function
  loopForIterator(): any {
    let counter = 2;

    return {
      next: (): any => {
        return {
          value: 'test' + counter,
          done: counter <= -1
        };
      }
    };
  }
}

const instance = new TestClass();

const properties = [];
for (let i of instance) {
  properties.push(i);
}

console.log(properties);

/* Output
[ 'test1', 'test0' ]
*/
  • Javascript
const { ClassLoop } = require('class-loop');
class TestClass extends ClassLoop {
  constructor() {
    super();
    this.property0 = 'prop0';
    this.property1 = 'prop1';
  }

  // Write your own loop function
  loopForIterator(): any {
    let counter = 2;

    return {
      next: (): any => {
        return {
          value: 'test' + counter,
          done: counter <= -1
        };
      }
    };
  }
}

const instance = new TestClass();

const properties = [];
for (let i of instance) {
  properties.push(i);
}

console.log(properties);

/* Output
[ 'test1', 'test0' ]
*/