In Javascript, given a generator object, how do I get it to output the name of the generator function that returned back that generator object?
In other words:
function* thisIsMyName(i) {
yield i;
}
const gen = thisIsMyName(10);
console.log(gen.name); // How do I get this to output "thisIsMyName" using only the gen object?
Calling gen.name
doesn't work as it isn't a function but a generator object
I am afraid you cannot access it like that because the reference to the function that generated this generator is stored in a property defined by a symbol. Symbols are unique and cannot be recreated (but nut all the time, see Symbol.for
). Meaning that if you don't have the reference to a symbol you cannot get its value.
Object.getOwnPropertySymbols()
does not return the native ones.
You can see however the symbol props in the console when inspecting the instance:
You can solve this however with a wrapper function, meaning a function that will return both the generator and the generator function:
function thisIsMyName(value){
const generatorFunction = function* thisIsMyName(i) {
yield i;
}
return {
generator : generatorFunction(value),
generatorFunction: generatorFunction
}
}
const gen = thisIsMyName(10);
console.log(gen.generatorFunction.name) // prints thisIsMyName
console.log(gen.generator.next()) // prints {value: 10, done: false}