Home > Mobile >  TypeScript: Elegant way to write single line helper functions
TypeScript: Elegant way to write single line helper functions

Time:11-21

I have a simple helper / util sort of class where there are some one/two liner utilities which I am planning to use across the code.

I am using Nest Js/Node Js with TypeScript.

I am just thinking how better, elegantly I can write these helper methods, preferably in a one-liner sort of .. sweet and nice.

My attempt so far

import { Injectable } from '@nestjs/common';

@Injectable()
export class HelperOperations {
    static zones(region: string): string[] {
        return region.split(',', 2);
    }

    static instanceNames(name: string): string[] {
        return [`${name}-vm1`, `${name}-vm2`];
    }

    static mediatorName(name): string {
        return `${name}-mediator`;
    }

    static mediatorZone(region: string): string {
        return region.split(",").pop();
    }

    static zoneNamePair(name, region): [string, string][] {
        const zoneNamePair: [string, string][] = [];
        const zones = HelperOperations.zones(region);
        HelperOperations.instanceNames(name).map((instName, i) => zoneNamePair.push([instName, zones[i]]));
        return zoneNamePair;
    }
}

Expected Outcome:

  • Better, elegant way to rewrite this class for betterment, of course strongly typed.

CodePudding user response:

Generally (dunno about Nest) this is done with exports or with namespaces

export const zones = (region: string) => region.split(',', 2);

export namespace z1 {
  export const zones = (region: string) => region.split(',', 2);
}
////////////
import {zones} from './z'
import * az z0 from './z'
import {z1} from './z'

zones('a')
z0.zones('a')
z1.zones('a')
  • Related