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}
From the comments:
You would need to create an intermediate factory that passed a reference to the function as well as the returned generator object
Not really usefull, but it may be something like:
const someGenerator = {
*thisIsMyName(i = 1, limit = 10) {
while (i < limit) {
yield i++;
}
},
get name() {return this.thisIsMyName.name},
};
const myGen = { name: someGenerator.name, i: someGenerator.thisIsMyName(15, 20)};
console.log(myGen.i.next().value, myGen.name);
Or ...
function createGenerator(name, min = 1, max = 10) {
function* xGen() {
while (min < max) {
yield min++;
}
};
return {gen: xGen(), name,};
};
const myGen = createGenerator(`myName`, 15, 20);
const values = [];
let nxt = {};
while (!nxt.done) {
nxt = myGen.gen.next();
!nxt.done && values.push(nxt.value);
}
console.log(values.join(`, `), `\nmyGen.name = '${myGen.name}'`);