【发布时间】:2016-12-06 12:38:23
【问题描述】:
我有这段 146 字节的 Javascript 代码(使用 jQuery):
$("#b").click(s=>{t=$("#a").val();o=[...t];for(p=0;p<t.length;p++){r=Math.random();if(.1>r)if(.03>r)o[p]=t[p--];else r>.07?o[p]="":o[p]+=t[p]}$("p").html(o)})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="a" placeholder="Insert here some text"/>
<button id="b">Generate typos</button>
<p></p>
基本上发生的情况是,当您单击按钮时,插入文本的每个字母都有 10% 的机会出现拼写错误,将字母替换为前一个字母或消失。
这段代码基于this codegolf question,但我已根据个人喜好修改了问题。
有什么方法可以减少用于 Javascript 代码的字节数? 注意:我不需要任何安全改进或性能改进。
这里是 Javascript 代码的整理版本,以便理解所写的内容:
$("#b").click(s => { //onclick
t = $("#a").val(); //get value of input
o = [...t]; //create array with each char in t as an index
for (p in o) { //loop through o
r = Math.random(); //generate random number
if (.1 > r) //if the random number is lower than 0.1 (~10% chance)
if (.03 > r) o[p] = t[p--]; //if the random number is lower than 0.03
else r > .07 ? o[p] = "" : o[p] += t[p] //else check if the random number is higher than 0.07
} //closing for loop
$("p").html(o) //replace content in p tags
})
更新:我已将其改进到我所知的最大值(137 字节):
$("#b").click(a=>{t=$("#a").val(),o=[...t];for(p in o)r=Math.random(),.1>r&&(.03>r?o[p]=t[p--]:r>.07?o[p]="":o[p]+=t[p]);$("p").html(o)})
整理如下:
$("#b").click( //onclick
a => { //arrow function
t = $("#a").val(), //get value of #a
o = [...t]; //make t an array
for (p in o) //loop through the array
r = Math.random(), //generate random number
.1 > r //if the number is smaller than 0.1
&& //and
(.03 > r ? o[p] = t[p--] : r > .07 ? o[p] = "" : o[p] += t[p]);//check if the number is smaller than 0.03 else check if number is smaller than 0.7
$("p").html(o)//write to p tag
})
【问题讨论】:
-
如果你觉得 146 字节太多了,你肯定对 jQuery 的大小也很不满意 :) 你为什么要担心这么小的脚本?
-
You could replace
Math.random()with 0.4. 这将节省 10 个字节,并且可能与此问题的任何其他答案一样多地提供实际帮助。 -
这里没有什么可以回答的。这适合代码高尔夫。
-
错了,codegolf 是关于基于最小字节数的问题创建代码,这是关于减少现有代码。
-
也许它在任何地方都不相关。 IMO 这是开放式的,不是任何人都可能再次需要的实际定义的问题。所以它可能对你有利,但对别人没有好处
标签: javascript jquery minify