函数式编程

48 阅读1分钟

函数式编程 中的函数指的不是程序中的函数(方法),而是数据中的函数即映射关系,例如:y = sin(x), x 和 y的关系。

相同的输入始终要得到相同的输出(纯函数)

函数式编程用来描述数据(函数)之间的映射。

函数是一等公民 高级函数 闭包

函数是一等公民: 1、函数可以存储在变量中, 2、函数作为参数, 3、函数作为返回值

//把函数赋值给变量

let fn = function(){ console.log('hello first-class function') }

// 示例

const BlogController = {
 index(posts){ return Views.index(posts)},
 show(post) { return View.index(post)},
 create(attrs){ return View.create(attrs)},
 update(post,attrs){return Db.update(post,attrs)},
 destroy(post){return Db.destory(post)}
}

//优化

const BlogController = {
 index:Views.index,
 show: View.index,
 create: View.create,
 update: Db.update,
 destroy: Db.destory
}

高阶函数

1、 可以把函数作为参数传递给另一个函数。

2、可以把函数作为另一个函数的返回值

// forEach
function forEach(array,fn){
    for(let i=0; i<array.length;i++){
        fn(array[i])
    }
}
//filter
function filter(array,fn){
    let result = []
    for(let i = 0; i <array.length ; i++) {
        if(fn(array[i])){
           result.push(array[i])
        }
    }
    return result
}