Tips from open-source: Generator function in Javascript.
As I was reading the Next.js source code, I saw a function name prefixed with "*". My first thought was “Is this a ponter in Javascript?”. After some research on Google, I found that these functions prefixed with "*" are called generator functions. I do not know about generator functions in Javascript until now.
Next.js source code has these generator functions defined in a class as shown below:
Keep in mind that normally when you define these generator functions outside a class, they have the following syntax:
// source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*function* generator(i) { yield i; yield i + 10; yield i + 20;}const gen = generator(10);console.log(gen.next().value);// Expected output: 10console.log(gen.next().value);// Expected output: 20console.log(gen.next().value);
Note: You can declare a generator like this — function generator() or function generator(). * can be separated with a white space or a line terminator.
public *keys(): IterableIterator<string> { for (const key of Object.keys(this.headers)) { const name = key.toLowerCase() yield name } }
This code snippet is from header.ts in Next.js source code. I asked myself a question “Why a keys() function is a generator function?”
I pasted this code in the ChatGPT and it introduced me to a term “Memory efficiency”. Hang on a minute, how?
Copy the below and paste in your browser
const exampleObject = { firstName: "John", lastName: "Doe", age: 30};// Implementing keys() method using a generator functionexampleObject.keys = function* () { for (const key in this) { yield key; }};// Now, you can iterate over the keys of exampleObject using a for...of loopfor (const key of exampleObject.keys()) { console.log(key);}// output:firstNameVM247:16 lastNameVM247:16 ageVM247:16 keys
But if you try to log the keys(), the following are the results:
Instead of generating all keys at once and storing them in an array, a generator function produces keys on-the-fly as they are requested.
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.
function* keys(), turns out is a generator function, not a pointer in anyway. You want to use this when you want to generate keys, entries, values on the fly.