const makeHero = (name, alias, abilities) => {
const hero = {};
hero.name = name;
hero.alias = alias;
hero.abilities = abilities;
hero.assemble = function () {
avengers.includes(this)
? console.log(
`${this.alias} has already been assembled into the
Avengers`
)
: avengers.push(this);
return avengers;
};
hero.disassemble = function () {
const heroToRemove = avengers.findIndex(
(hero) => hero === this
);
heroToRemove === -1
? console.log(
`${this.alias} has already been disassembled from the
Avengers`
)
: avengers.splice(heroToRemove, 1);
return avengers;
};
return hero;
}
I created an object inside a factory function and I want to store it inside an array called avengers which is outside of the factory function so it can check all the conditions if I add multiple objects inside the array.
I was wondering how can i loop through the array so it also checks the function condition inside assemble and disassemble because when i log the array console returns - assemble: [function], disassemble [function]
I don’t understand what you mean here.
It seems that being assembled just means being in the avengers
array here.
So any hero object in the avengers
array would count as being assembled;
you don’t have a separate property to check or record whether a hero has been assembled.
Using your code:
const avengers = [];
const makeHero = (name, alias, abilities) => {
const hero = {};
hero.name = name;
hero.alias = alias;
hero.abilities = abilities;
hero.assemble = function () {
avengers.includes(this)
? console.log(
`${this.alias} has already been assembled into the Avengers`
)
: avengers.push(this);
return avengers;
};
hero.disassemble = function () {
const heroToRemove = avengers.findIndex(
(hero) => hero === this
);
heroToRemove === -1
? console.log(
`${this.alias} has already been disassembled from the Avengers`
)
: avengers.splice(heroToRemove, 1);
return avengers;
};
return hero;
};
const thor = makeHero("Thor", "Sparklefingers", ["Lightning", "hammer"]);
const hulk = makeHero("Bruce Banner", "Hulk", ["Smash", "invulnerability"]);
const captain = makeHero("Steve Rogers", "Captain America", ["strength", "shield"]);
captain.assemble();
thor.assemble();
hulk.assemble();
hulk.disassemble();
console.log("assembled Avengers:");
console.log(avengers.map(hero => hero.name));
const heroes = [thor, hulk, captain];
for (let hero of heroes) {
if (avengers.includes(hero)) {
console.log(`${hero.name} is assembled.`);
}
else {
console.log(`${hero.name} is not assembled.`);
}
}
When iterating through each hero
in an array of heroes, I had:
if (avengers.includes(hero)) {
console.log(`${hero.name} is assembled.`);
}
else {
console.log(`${hero.name} is not assembled.`);
}
to display which hero was assembled (meaning in avengers
).
1 Like