Search code examples
javascriptreactjsstorybookdestructuring

Can a destructed assignment return any number of objects?


I have a series of Storybook stories, and a function that returns a ComponentStory object. I'm trying to think of a succinct way to clone a bunch of stories, without having something like this:

export const Default = bindStory(Template);
export const WithError = bindStory(Template);
export const AnotherOne = bindStory(Template);

Some of the files have 20, 30, stories in them, so this could get unwieldy and not very DRY. I was wondering if there would be a way to define it like this:

export const [Default, WithError, AnotherOne] = bindStories(Template);

And then apply the .args to those individual objects. The issue would be ensuring the bindStories function always returns enough instances of the ComponentStory object.


Solution

  • To do this you can make use of infinite iterators. Destructuring assignment works on any iterable and so an infinite iterator allows for as many objects as you like. This means you don't need to pass length and the variables will never be undefined.

    function* getObjects() {
      const object = {
        lorem: 1
      };
    
      while (true) {
        yield { ...object };
      }
    };
    
    const [first, second, third, fourth] = getObjects();
    console.log({
      first,
      second,
      third,
      fourth
    });