javascript - 是否可以在打字稿中制作像这样工作的模块?
问题描述
我想创建一个可以通过这种方式调用的函数/模块/类:
const myvar = MyModule('a parameter').methodA().methodB().methodC();
//but also this should work
const myvar = MyModule('a parameter').methodC().methodA();
换句话说,要制作一个可以接受不同数量的“回调”的静态模块?以任何可能的顺序。
我不想创建类的实例,我希望每个方法都返回一个字符串。
这甚至可能吗?
编辑
要更清楚。我想要一种使用不同方法将字符串作为输入处理的方法。每个方法都以某种方式处理字符串并将结果返回给下一个方法。如果没有附加方法,它将返回字符串。
也许我在问一些不可能的事情。但也许存在具有相似结构和相同结果的东西。
解决方案
这是我现在的解决方案:
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();
推荐阅读
- python-3.x - 如何以简单的方式进行累积平均值和计数
- wordpress - 如何传递链接的跟踪 ID 并将它们添加到 wordpress 页面上的出站链接
- mysql - MYSQL - 无法创建外部密钥
- unity3d - 字符串构造函数不能在统一 c# 中工作
- github - Github - 如何将我的项目提交到现有存储库的子文件夹/目录?
- machine-learning - 在 NEAT 算法中向结构添加节点/连接
- python - 如何将 apscheduler 执行器保留在不同的应用程序中并在不同的应用程序中添加作业
- php - 在 Symfony4 中将 Doctrine-Entity 依赖注入到服务中?
- android - 片段已经添加了带有单例对话框的异常
- ios - Flutter 包构建错误“找不到 swift 文件”