Home > Enterprise >  What prototype function does `Array.prototype.push` use on the passed elements
What prototype function does `Array.prototype.push` use on the passed elements

Time:11-15

I have a resolver class that does some data validation and I want to also use it so it can be pushed into an array. Obviously I don't want to push the class but a specific object structure into the array.

type RoleReward = {
  roleId: Snowflake;
  rewardName: string;
  redeemed: boolean;
}

const resolver = new BaseRoleResolver();
const allRewards = new Array<RoelReward>();

allRewards.push(resolver);

and the resolvers all use this base class

export class BaseRoleResolver {
  roleId: Snowflake;
  rewardName: string;
  redeemed: boolean = false;

  (...)

  valueOf() {
    return {
      roleId: this.roleId,
      rewardName: this.rewardName,
      redeemed: this.redeemed,
    };
  }
}

Can I make use of Javascript calling some prototype function on the class that I can just overwrite to return the custom object format instead of the entire class object?

EDIT: Clarified first code snippet

CodePudding user response:

What prototype function does Array.prototype.push use on the passed elements

None. It just puts whatever values you pass to it into the array.

Can I make use of Javascript calling some method on the object that I can just overwrite?

No.

I don't want to push the class but a specific object structure into the array.

Then you will have to write your code so it does that:

  for (const resolver of roleResolvers) {
    if (
      (await resolver.qualifiesForReward(validOrders, email)) &&
      !resolver.alreadyRedeemed(allRewards)
    ) {
      allRewards.push(resolver.valueOf());
//                             ^^^^^^^^^
    }
  }
  • Related