RMMV ES6 Part 2 : Generator Functions

Introduction

Developing plugins RPGMaker MV can be difficult; we can add a lot of complexity with the code that we add. Continuing our ES6 incentive to learn new things and features available to us in RMMV. Today, I bring to you generator functions.

Generator Functions

Generator functions are functions that can be used to execute things one step at a time; you can enter and then reenter the function at a later time. One of the other cool things is that, a generator function once it’s done processing, it can’t be processed, or accessed again. This can be really effective if you want to run something, step by step within your instructions. Here’s an example of a generator function.

Example

function* idMaker() {

 let index = 0;

 while(index <  3)

   yield index++

}

This function returns the index multiple times with each iteration, but you have complete control of when the next iteration will start. That alone is very powerful. This is just a trivial case, but it has a few applications. One of the applications being accessing the same array after running some other code.

Example 2

var nameList = ['Ryan', 'Ben'];


function* arrayChecker(i) {

let index = 0;

while(index < 2) {

 index++;

 yield  i;

}

}
//Create gen with our specified value to return once we get to yield
//It will return Ben

var gen = arrayChecker(nameList[1]);

gen.next(); //Returns Ben

gen.next(); //Returns Ben once again

gen.next(); //Will return undefined because it’s done executing

As you can see, we can make our function execute multiple times step by step, to return whatever we want at each iteration. It’s like having a for loop without the messy parts of it continuing execution when we don’t want it to. One important thing to note is that the variable you pass when storing it in a variable is essentially bound to the function. This can be great for processing important information at different times.

Conclusion

Generator functions can be fairly useful; it can be a step up from bounded functions, allowing for some interesting effects. And, it even has properties that can tell you when the generator is done processing.

Now, I know that making the switch to ES5 to ES6 can be hard, but you can use both to maximize your productivity as a developer.

If you want to see more tutorials like this, stay tuned to the blog, or send me a message on twitter @EISKino if you have any ideas for tutorials. I hope you have a wonderful day!

Leave a Reply

Your email address will not be published.