GitHub: https://github.com/YuanSa/mnl.js
你是否为函数参数过多、顺序混乱头疼过?
想解决这个问题,在python中可以为指定参数赋值,在JavaScript中则可以传递参数对象。
本文提出另一种解决方法:仿生命名法 (Mock Natrual Language)。
仿生命名法是一种给函数命名的方法,让你可以用接近自然语言的语法给函数命名。
仿生命名法很简单,即在函数名内部任意位置插入括号。如:
function deleteThe(i)ItemFrom(arr) {
return arr.splice(i, 1)
}
由于与现有JavaScript语法不兼容,我们需要一个编译器进行转换。
目前的策略是将括号替换为__x__
,参数列表依次添加到函数名末尾。
而出于兼容性考虑,函数名末尾的__x__
会被删除。
示例
mnl语法
let myHeart = ['kind', 'evil', 'happy'];
console.log(`I born with ${myHeart.join(', ')}.`);
remove('evil')from(myHeart);
console.log(`Now, I have only ${myHeart.join(', ')} in my heart.`);
function remove(item)from(array) {
array.splice(array.indexOf(item), 1);
console.log(`Now I removed the ${item} in it.`);
}
编译后(js语法)
let myHeart = ["kind", "evil", "happy"];
console.log(`I born with ${myHeart.join(", ")}.`);
remove__x__from("evil", myHeart);
console.log(`Now, I have only ${myHeart.join(", ")} in my heart.`);
function remove__x__from(item, array) {
array.splice(array.indexOf(item), 1);
console.log(`Now I removed the ${item} in it.`);
}
运行结果
I born with kind, evil, happy.
Now I removed the evil in it.
Now, I have only kind, happy in my heart.
编译器
为实现功能,我用js写了一个编译器,可用node运行。
由于笔者能力有限,目前的demo编译器不能完美编译。目前已知有如下bugs:
- 字符串内的代码也会被编译
详情请见mnl.js的GitHub页面:https://github.com/YuanSa/mnl.js
欢迎指教与合作。