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
欢送指教与单干。