How to apply swith for case or polymorphism?

I have an object that contains the user roles:

let roles = {write: true, read: false, send: true}

Now I check roles using if:

if (roles.write) {
   // Call method
}

if (roles.read) {
   // Call method
}

if (roles.send) {
   //
}

Problem is that new roles are added sometimes. How to do that elegant?

Replace conditional with polymorphism.

I have tried this:

 interface UserRights {
   CustomLayers: boolean
}


abstract class Layer {
    protected abstract load(): void;

    abstract get(): Layer[];

    protected layers: any[] = [];

    constructor(protected userRoles: UserRights) {

    }
}

class CommonLayers extends Layer {
    
    constructor(protected userRoles: UserRights) {
        super(userRoles);
        this.load();
    }

    protected load() {
        this.layers = [4, 5];  
    }

      get(): Layer[]{
        return this.layers;
    }
}

class ThematicLayers extends Layer {
    
    constructor(protected userRoles: UserRights) {
        super(userRoles);
        this.load();
    }

    protected load() {
        if (this.userRoles.CustomLayers) 
        setTimeout(() => this.layers = [1, 2, 3], 5000);
            
    }

    get(): Layer[]{
        return this.layers;
    }
}

class LayersService {
    private layers: any[] = [];
    private userRoles = {
        CustomLayers: true,
    }

    getLayers() {
        return this.layers;
    }

    constructor() {
         this.layers = [new CommonLayers(this.userRoles), new ThematicLayers(this.userRoles)].map((layer: Layer) => [...layer.get()]);
    }
}

const service = new LayersService();
console.log(service.getLayers());

Problem is that I dont know how to return async data []` here:

`.map((layer: Layer) => [...layer.get()]);`, because `load()` can be sync or async

I have result as array of numbers

25 thoughts on “How to apply swith for case or polymorphism?”