美文网首页
2019-06-09

2019-06-09

作者: 将军肚 | 来源:发表于2019-06-09 20:29 被阅读0次
    
    // ===== 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)
    
    
    

    相关文章

      网友评论

          本文标题:2019-06-09

          本文链接:https://www.haomeiwen.com/subject/ndanxctx.html