javascriptiteratorjavascript-objects

How create custom iterator that skips empty value in Javascript


Cusomt iterator in Javascript

Hi, I would like to create a Javascript class that overrides Symbol.iterator in order to skip the data that are null or undefined.

Example

  const simple = new SimpleClass([
    {
      fields: `a`,
    },
    {
      fields: `b`,
    },
    {
      fields: undefined,
    },
    {
      fields: null,
    },
    {
      fields: `e`,
    },
  ]);

  for (const val of simple) {
    console.log(val); // a b e
  }

Here is where I've started: Defining an iterable with a class

Can you help me to draft a solution for my use-case?

Thanks!


Solution

  • class SimpleClass {
      #items
      constructor(items) {
        this.#items = items
      }
    
      *[Symbol.iterator]() {
        for (const item of this.#items) {
          if (item.fields !== null && item.fields !== undefined) {
            yield item.fields
          }
        }
      }
    }
    
    const simple = new SimpleClass([{
        fields: `a`,
      },
      {
        fields: `b`,
      },
      {
        fields: undefined,
      },
      {
        fields: null,
      },
      {
        fields: `e`,
      },
    ]);
    
    for (const val of simple) {
      console.log(val); // a b e
    }