function btoa(input) {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var str = String(input);
for (var block, charCode, idx = 0, map = chars, output = ''; str.charAt(idx | 0) || ((map = '='), idx % 1); output += map.charAt(63 & (block >> (8 - (idx % 1) * 8)))) {
charCode = str.charCodeAt((idx += 3 / 4));
if (charCode <= 0xff) {
block = (block << 8) | charCode;
}
}
return output;
}
btoa(pako.gzip(decodeURIComponent(JSON.stringify(data)), { to: 'string' }));
尾调用优化条件: 代码在严格模式下执行;外部函数的返回值是对尾调用函数的调用;尾调用函数返回后不需要执行额外的逻辑;尾调用函数不是引用外部函数作用域中自由变量的闭包。
// 这样重构之后,就可以满足尾调用优化的所有条件,再调用 fib(1000)就不会对浏览器造成威胁了。
function fib(n) {
return fibImpl(0, 1, n);
}
function fibImpl(a, b, n) {
if (n === 0) {
return a;
}
return fibImpl(b, a + b, n - 1);
}