优化小常数范围 map()
语境
map()
for
[ 0 .. N− 1 ]
for(i = 0; i < 10; i++) {
do_something_with(i);
}
可以替换为:
[...Array(10).keys()].map(i => do_something_with(i))
或更常见的是:
[...Array(10)].map((_, i) => do_something_with(i))
Array(N)
N 是一个小常数。
一系列优化 [ 0 .. N− 1 ],带柜台
下面总结了计数器时较短的替代方法 一世 在回调中使用:
N | Method | Example | Length
------------+--------------------------------------+---------------------------------+-------
N ≤ 6 | use a raw array of integers | [0,1,2,3].map(i=>F(i)) | 2N+10
N = 7 | use either a raw array of integers | [0,1,2,3,4,5,6].map(i=>F(i)) | 24
| or a string if your code can operate | [...'0123456'].map(i=>F(i)) | 23
| with characters rather than integers | |
8 ≤ N ≤ 9 | use scientific notation 1e[N-1] | [...1e7+''].map((_,i)=>F(i)) | 24
N = 10 | use scientific notation 1e9 | [...1e9+''].map((_,i)=>F(i)) | 24
| or the ES7 expression 2**29+'4' if | [...2**29+'4'].map(i=>F(i)) | 23
| the order doesn't matter and your | |
| code can operate with characters | (order: 5,3,6,8,7,0,9,1,2,4) |
| rather than integers | |
11 ≤ N ≤ 17 | use scientific notation 1e[N-1] | [...1e12+''].map((_,i)=>F(i)) | 25
N = 18 | use the fraction 1/3 | [...1/3+''].map((_,i)=>F(i)) | 24
N = 19 | use the fraction 1/6 | [...1/6+''].map((_,i)=>F(i)) | 24
20 ≤ N ≤ 21 | use scientific notation 1e[N-1] | [...1e20+''].map((_,i)=>F(i)) | 25
N = 22 | use scientific notation -1e20 | [...-1e20+''].map((_,i)=>F(i)) | 26
23 ≤ N ≤ 99 | use Array(N) | [...Array(23)].map((_,i)=>F(i)) | 27
NB:F(i)
不计算回调代码的长度。
优化范围 [ 1..9 ],带柜台
如果您想遍历整个范围 [ 1..9 ] 而且顺序无关紧要,您可以使用以下ES7表达式(前提是您的代码可以使用字符而不是整数进行操作):
[...17**6+'8'].map(i=>F(i)) // order: 2,4,1,3,7,5,6,9,8; length: 23
无计数器优化
如果只需要迭代,可以使用以下方法 ñ 次,无需使用计数器:
N | Method | Example | Length
------------+--------------------------------------+---------------------------------+-------
N ≤ 5 | use a raw array of integers | [0,0,0,0].map(_=>F()) | 2N+10
6 ≤ N ≤ 10 | use scientific notation 1e[N-1] | [...1e7+''].map(_=>F()) | 20
11 ≤ N ≤ 17 | use scientific notation 1e[N-1] | [...1e12+''].map(_=>F()) | 21
N = 18 | use the fraction 1/3 | [...1/3+''].map(_=>F()) | 20
N = 19 | use the fraction 1/6 | [...1/6+''].map(_=>F()) | 20
20 ≤ N ≤ 21 | use scientific notation 1e[N-1] | [...1e20+''].map(_=>F()) | 21
N = 22 | use scientific notation -1e20 | [...-1e20+''].map(_=>F()) | 22
23 ≤ N ≤ 99 | use Array(N) | [...Array(23)].map(_=>F()) | 23
NB:F()
不计算回调代码的长度。