// ===== every =====
const every = (arr, fn) => {
let result = true;
for(let i=0; i<arr.length; i++){
result = result && fn(arr[i])
}
return result;
}
// ===== some =====
const some = (arr, fn) => {
let result = false;
for(let i=0; i<arr.length; i++){
result = result || fn(arr[i])
}
return result;
}
// ===== sortBy =====
const sortBy = (property) => {
return (a, b) => {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result;
}
}
people.sort(sortBy('firstname'))
// =====闭包 =====
var fn = (arg) => {
let outer = "Visible"
let innerFn = () => {
console.log(outer)
console.log(arg)
}
return innerFn
}
var closureFn = fn(5)
closureFn()
// Visible
// 5
// ===== tap =====
const tap = (value) =>
(fn) => {
typeof(fn) === 'function' && fn(value),
console.log(value)
}
tap("fun")((it) => console.log("Value is ", it))
forEach([1,2,3],(a)=>
tap(a)(()=>{
console.log(a)
}
)
)
// ===== unary =====
const unary = (fn) => {
console.log(fn)
return fn.length === 1
? fn
: (arg) => fn(arg)
}
['1','2','3'].map(unary(parseInt))
// [1,2,3]
// ===== once =====
const once = (fn) => {
let done = false;
return function(){
return done ? undefined: ((done = true), fn.apply(this, arguments))
}
}
// ===== factorial =====
var factorial = (n) => {
if(n===0){
return 1
}
return n * factorial(n - 1)
}
factorial(4)
//24
// ===== memoized =====
const memoized = (fn) => {
const lookupTable = {}
return (arg) => lookupTable[arg] || (lookupTable[arg] = fn(arg))
}
let fastFactorial = memoized((n)=>{
if(n===0){
return 1;
}
return n * fastFactorial(n - 1)
})
fastFactorial(5)
网友评论