Write a Generator Function to Generate the Alphabet

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 3 years ago

When you need to generate a data set, a generator function is often the correct solution. A generator function is defined with function* and then you yield each result you want out of the function when you call it. Generators pair well with the ... operator inside of Array because they serve as iterators which can be called until all their results are exhausted.

Instructor: [00:00] If you look at the string of A and check the character code, you'll see it gives us back a 97. If you check out Z, we'll get back 122. To get all the letters in between, we have to start at A and end at Z.

[00:20] We can create a generator for that, so function* generate alphabet. We'll let our index start at A. A, character code at zero. Zero is referring to this first letter in the string. Then the end will be Z, character code at +1 because we're zero-based, so we have to go one past the end.

[00:50] Then, we can create a while loop, saying while I is less than end, we want to yield a string from the character code of I. For example, if you take A, which gives us 97, and you take string character code from 97, you'll see we get A back. Then after we yield that character, which will go A, B, C, D, and on and on, we'll do I++. Then, we have our generator.

[01:33] To get our alphabet out of there, we can say let alphabet=an array and then simply spread the generate alphabet function and invoke it. Then, the result will be A, B, C, D, E, F, G, all the way to Z because this function works as an iterator which yields. When we spread this iterator into an array, we get an array of each of those letters.

Mohsin Ul Haq
Mohsin Ul Haq
~ 5 years ago

how is it better than returning an array containing all the alphabets created using the same loop?

Markdown supported.
Become a member to join the discussionEnroll Today