Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

EDIT: Clarified first code snippet

>Solution :

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());
//                             ^^^^^^^^^
    }
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading