NewbieProgrammer
NewbieProgrammer

Reputation: 89

cache within getters/setters?

If I have a getter like this:

export class foo{
    aaa: number;
    bbb: number;
    ccc: number;

    constructor(){
        //whatever
    }

    get getHeight(f: number){
        return (f + 16) * Math.ceil(Math.round(Math.tan(aaa) + bbb/2) * ccc);
    }
}

where aaa, bbb, and ccc is a constant that does not get changed during runtime.

I have to call the getter multiple times from other classes during runtime, so I want to be able to reduce performance as much as possible by "cache"ing Math.ceil(Math.round(Math.tan(aaa) + bbb/2) * ccc). Is it possible to do this without having to make a completely new variable inside the foo class?

*bonus question: Is it possible in typescript to combine same variable types into one? like in java, I can do something like:

int aaa, bbb, ccc;

but it seems like typescript doesnt allow that.

Upvotes: 4

Views: 3655

Answers (3)

Markus
Markus

Reputation: 4149

I'm not sure what you trying to do. But how is that? Playground

export class foo{
    /* Is not visible outside of foo. */
    private static factor = Math.ceil(Math.round(Math.tan(foo.aaa) + foo.bbb/2) * foo.ccc);

    public constructor(){
        //whatever
    }

    public getHeight(f: number){
        return (f + 16) * foo.factor;
    }
}

export module foo {
    /* Use module mixing for constant variables, */
    export const aaa = 1;
    export const bbb = 2;
    export const ccc = 3;
}

Or like this? Playground

export class foo{

    /* or readonly propierties. */
    public get aaa(){ return 1;};
    public get bbb(){ return 2;};
    public get ccc(){ return 3;};

    /* Is still not visible outside of foo. */
    private static factor = Math.ceil(Math.round(Math.tan(foo.aaa) + foo.bbb/2) * foo.ccc);

    public constructor(){
        //whatever
    }

    public getHeight(f: number){
        return (f + 16) * foo2.factor;
    }
}

Upvotes: 0

gilamran
gilamran

Reputation: 7304

Sounds like you should export this calculation to an external static class that does this calculation one time on the class definition like this:

class Calculator {
    static a : number = 5;
    static b : number = 6;
    static c : number = 7;
    static height : number = Math.ceil(Math.round(Math.tan(Calculator.a) + Calculator.b/2) * Calculator.c);
}

export class foo{

    constructor(){
        //whatever
    }

    getHeight(f: number){
        return (f + 16) * Calculator.height;
    }
}

Upvotes: 0

basarat
basarat

Reputation: 276085

Is it possible to do this without having to make a completely new variable inside the foo class

nope. TypeScript doesn't have static function local variables which is effectively what you are asking for.

Is it possible in typescript to combine same variable types into one? like in java, I can do something like

Not a part of the standard way in TypeScript + I don't have a clever trick here.

Upvotes: 2

Related Questions