js函数式编程最佳实践 - 持续更新

函数式编程最佳实践

学习文档

数组字串处理
function addString(el){
  return el + "0";
}
var newArr = arr.map(addString).join("");
var arr = ["1","2","3","4"];
console.log(newArr);
创建 tags
// 创建 - 单个
function createTag(val) {
    return '<div class = "dp-tag" >' + val.text + '</div>';
}
// 创建 - 全部,三个版本
// 1
function createAllTag(params) {
    var str = "";
    params.forEach(function (x) {
        str += createTag(x.text);
    })
    return str;
}
// 2
function createAllTag(params) {
    return params.map(function (x) {
        return createTag(x.text);
    }).join("");
}
// 3
function createAllTag(params) {
    return params.reduce(function (tags, x) {
        return tags += createTag(x.text);
    }, "");}
}
var str = createAllTag([{text:111},{text:222}]);
$("body").html(str)
创建表格
function createTableTd(td){
  return "<td>" + td + "</td>";
}
function createTableTr(row){
  return "<tr>" + row.map(createTableTd).join("") + "</tr>";
}
function createTable(data){
  return "<table>" + data.map(createTableTr).join("") + "</table>";
}

var data = [[1,2],[3,4]];
var res = createTable(data);
console.log(res);

实现一个展示/收起功能
var collectBoard = {
  dom:$("#board"),
  data:[],
  show:false,
  updateData:function(){
    this.data = [1,2,3]; 
  },
  toggle:function(){
    this.show = !this.show;
    if(this.show){
      this.updateData();
    }
    console.log(this.show,this.data);
  },
  init:function(){
    var that = this;
    this.dom.click(function(){
      that.toggle();
    })
  }
}
collectBoard.init();
倾向于对象遍历而不是Switch语句
//倾向于对象遍历而不是Switch语句
const fruitColor = {
  red: ['apple', 'strawberry'],
  yellow: ['banana', 'pineapple'],
  purple: ['grape', 'plum']
};

function test(color) {
  return fruitColor[color] || [];
}
只执行一次的函数(基于隋性单例模式)
// 能用的包装函数
var getSignle = function(fn){
  var res = null;
  return function(){
    // 理解 apply,即 fn 把传参的权力,让渡给了包装函数 getSignle
    return res || (res = fn.apply(this,arguments));
  }
};
var getName = function(){
  console.log(123);
  return "gs";
}
var onceGetName = getSignle(getName);
onceGetName();// 123 gs
onceGetName();// gs
onceGetName();// gs
通过高阶函数,传递 this对象值
//例一
var data = {
  domId:"wrap",
  ...
  // 通过高阶函数,传递 this.domId
  eventList:function(){
    var $domId = $("#"+this.domId);
    return {
      clickTag:function(){
        $domId.on("click","button",function(){
          $(this).remove();
        });
        this.clickTag = null;
      },
      clickToChangeFooter:function(){
        $domId.on("click","footer",function(){
          $(this).text("footer changed")
        });
        this.clickToChangeFooter = null;
      }
    }
  },
  // 不使用高阶函数,clickTag 函数中的this仅指向 clickTag 本身,且外层数据难以传递
  eventList:{
    clickTag:function(this.domId){
      $("#"+this.domId).on("click","button",function(){
        $(this).remove();
      });
      this.clickTag = null;
    }
  }
}
//例二
var obj = {
    a:1,
    b:function(){
        console.log(this)   
    }
}
// {a: 1, b: ƒ}
// this就是会指向最近的对象
编写函数实现链式调用

核心就是在函数尾部,返回那个对象

var student = {
  name:"zk",
  age:19,
  setName:function(name){
    this.name = name;
    return this;
  },
  setAge:function(age){
    this.age = age;
    return this;
  }
};

student.setName("gs").setAge(22);
console.log(student);
连续使用箭头函数
  • 只有最后是执行,其它均为参数,可以理解为柯里化
const splat = handle => (...array) => handle(array)
const fun = array => array.reduce((a, b) => a * b);
const res = splat(fun)(1, 2, 3, 4)

const add = a => b => c => a+b+c;
console.log(add(1)(2)(3))
更改一个嵌套对象数据的值
  • 利用this指向,减少引用对象层级
//这个模式,避免了出现 dp.data.treelist = dp.data.treelist.map(...)
var obj = {
  list:{
    data:[1,2,3],
    update:function(){
    //注意,this指向父级,而不是最外层对象
      this.data = this.data.map(function(x){
        return x * x;
      })
    }
  }
}
obj.list.update()
console.log(obj);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值