@JunQiu
2018-12-10T21:46:33.000000Z
字数 2807
阅读 1552
language_js
algorithm
summary_2018/12
const _ = require('lodash')
let list = [1, 2, 3, 4, 5]
// _.chain
const res = _
.chain(list)
.filter(n => n % 2 === 0)
.sum()
// wrap value
//console.log(res)
// 6
console.log(res.value())
list.push(8)
// 14 (The execution of chained methods is lazy),不会立即执行而是调用的时候再执行,比如等待资源加载完成
console.log(res.value())
let list1 = [1, 2, 3, 4, 5]
// _
const res1 = _(list1)
.filter(n => n % 2 === 0)
// [ 2, 4 ]
console.log(res1.value())
// wrap:filter is chainable
console.log(res1)
// 14 sum:not chainable
console.log(res1.sum())
function factorial(n) {
if (n === 1) {
return 1
}
return n*factorial(n - 1)
}
// 计算过程
factorial(5) = factorial(4) * 5
factorial(5) = factorial(3) * 4 * 5
factorial(5) = factorial(2) * 3 * 4 * 5
factorial(5) = factorial(1) * 2 * 3 * 4 * 5
factorial(5) = 1 * 2 * 3 * 4 * 5
// example
function factorial(n) {
// log stack information
console.trace()
if (n === 1) {
return 1
}
return n * factorial(n - 1)
}
factorial(3)
// log 进行了3次压栈调用
Trace
at factorial (/Users/qiujun/WebstormProjects/sad-e015/level-1-upgrade-ads-strategy/test.js:32:14)
at factorial (/Users/qiujun/WebstormProjects/sad-e015/level-1-upgrade-ads-strategy/test.js:32:14)
at factorial (/Users/qiujun/WebstormProjects/sad-e015/level-1-upgrade-ads-strategy/test.js:32:14)
at Object.<anonymous> (/Users/qiujun/WebstormProjects/sad-e015/level-1-upgrade-ads-strategy/test.js:35:1)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
// example
function factorial(n, total = 1) {
if (n === 0) {
return total
}
return factorial(n - 1, n * total)
}
// 过程factorial(3, 1)
factorial(3, 1)
factorial(2, 3)
factorial(1, 6)
在每一步运行中,上一个函数的结果会传到下一次调用的函数中。从而只保证只有一个栈在调用。
Tips:node移除了对尾递归的优化。
function factorial (n, total = 1) {
while (true) {
if (n === 0) {
return total
}
total = n * total
n = n - 1
}
}