Generate fixtures for Vue chart component with yield and iterator

highchart chart

Sometimes working on a Front-end side you need to write your Front-end code while Back-end actions are still not ready.
In this case, you would need to use on FE side, in order to not mess with BE. I have found relatively new ES6 features, as yieldand iterator comes in handy for .

Why do I need to generate fixtures for ?

For example, I need to feed such a chart with some random data for a given date range. Dates range should go from today and to 10 days in the past.

highchart line chart

highchart line chart

We also assume, that the data for each chart line will be requested from back-end action by a separate request and merged into some object on the front-end.
Just to make it easier for me, I also have prepared a list of some entity IDs which I display under the chart. When I click on the ID then I simulate a call to back-end and another line added to the chart.
That is how it looks like in action.

chart in action

chart in action

Generating fixtures with and iterator

Since we are dealing with Vue, I also have created some action in the Vuex store, which calls an API class method.
Inside this method, I just wait for my fixtures provider Promise to resolve and return the data.

return (new Provider).provide();

The most interesting part is inside the provider itself. Here I have used yieldtogether with the Symbol.iterator functionality to generate random data.

provideEntries is a generator. It works mostly the same as in PHP or any other language which supports generators.
I find it really great how you can assign any function which returns iterable to build-in Symbol.iterator functionality and turn your class into an iterable collection.
It works absolutely with any iterable in JS, like arrays, and for generator too.

In provide function, I just declare a new instance of Provider and use the spread operator ... on it. It makes JS iterate on each iterable collection entry and put it into an array.
In the case of Generator, it will generate all the possible outcome and stop when, according to JS iterators protocol, the generator will return internally something like

return { value: {your object}, done: true };

which is a signal for JS that iteration is over.

Then, in addition, I simulate the waiting time for the response. For that I use setTimeout a method with some random time to wait and return a Promise which I can await in my API class.
When the promise is resolved, I do the response merging with the current Vuex state inside the action method.