首页 > 解决方案 > 是否可以在打字稿中制作像这样工作的模块?

问题描述

我想创建一个可以通过这种方式调用的函数/模块/类:

const myvar = MyModule('a parameter').methodA().methodB().methodC();

//but also this should work

const myvar = MyModule('a parameter').methodC().methodA();

换句话说,要制作一个可以接受不同数量的“回调”的静态模块?以任何可能的顺序。

我不想创建类的实例,我希望每个方法都返回一个字符串。

这甚至可能吗?

编辑

要更清楚。我想要一种使用不同方法将字符串作为输入处理的方法。每个方法都以某种方式处理字符串并将结果返回给下一个方法。如果没有附加方法,它将返回字符串。

也许我在问一些不可能的事情。但也许存在具有相似结构和相同结果的东西。

标签: javascriptnode.jstypescriptcallback

解决方案


这是我现在的解决方案:

export default class sanitize {

    private _var:any = '';

    private static _instance:sanitize;

    private constructor(){}

    private static _g(){
        return this._instance || (this._instance = new this());
    }
    public static return(){
        const ret = this._g()._var;
        this._g()._var = '';
        return ret;
    }
    private static return_class(){
        return this;
    }
    private static check_string(){
        if(typeof this._g()._var != 'string')
            this.string(this._g()._var);
    }
    public static string(variable:any){
        if(typeof variable.toString != undefined)
            this._g()._var = variable.toString();
        else
            this._g()._var = '';
        return this.return_class();
    }
    public static alphanum(){
        this.check_string();
        this._g()._var = this._g()._var.replace(/[^\w\s]/gi, '');
        return this.return_class();
    }
    public static tolow(){
        this.check_string();
        this._g()._var = this._g()._var.toLowerCase();
        return this.return_class();
    }
    public static toup(){
        this.check_string();
        this._g()._var = this._g()._var.toUpperCase();
        return this.return_class();
    }
    public static subs(start:number, end:number){
        this.check_string();
        this._g()._var = this._g()._var.substring(start, end);
        return this.return_class();
    }
}
// And then I call

const san_str = sanitize.string('could be a number').alphanum().tolow().return();

推荐阅读