手写

sum

  1. // 步骤
  2. // 1. 利用闭包收集参数
  3. // 2. 使用reduce计算结果
  4. function addSum(){
  5. let args = [...arguments];
  6. // 收集参数
  7. function collectArgs(){
  8. args = [...args, ...arguments];
  9. return collectArgs;
  10. }
  11. // 计算结果
  12. collectArgs.valueOf = function(){
  13. return args.reduce((pre, cur) => pre + cur, 0)
  14. }
  15. return collectArgs;
  16. }
  17. console.log(addSum(1)(2)(3).valueOf()) // 6

偏函数

  1. // 偏函数是柯里化的子集
  2. // 固定一个参数
  3. function partial(fn, ...args) {
  4. return function(...newArgs) {
  5. return fn.apply(this, [...args, newArgs]);
  6. }
  7. }
  8. // 使用
  9. function add(num1, num2){
  10. return num1 + +num2 ;
  11. }
  12. // 普通函数转换为偏函数
  13. let addOne = partial(add, 1);
  14. console.log(addOne(2)); // 3
  15. console.log(addOne(3)); // 4

this输出问题

instanceof

  1. // instanceof 用于检测构造函数的prototype属性是否出现在某个实例对象的原型上
  2. function myInstanceof(left, right) {
  3. // left 为实例对象
  4. // right 为构造函数
  5. let leftProto = Object.getPrototypeOf(left);
  6. let RightProto = right.prototype;
  7. while (1){
  8. // 如果找到原型链的尽头还是没跳出,证明不是由该构造函数实例化的对象
  9. if(!leftProto) return false;
  10. if(leftProto === RightProto) return true;
  11. leftProto = Object.getPrototypeOf(leftProto);
  12. }
  13. }

create

  1. // Object.create方法用于创建对象
  2. // 第一个参数为传入的原型对象,所创建的对象的原型对象会指向传入的原型对象
  3. Object.myCreate = function(proto, propertiesObject) {
  4. // 参数校验
  5. if(typeof(proto) !== "object"){
  6. throw new Error("Proto is not an object")
  7. }
  8. function tempFn(){}
  9. tempFn.prototype = proto;
  10. let tempObj = new tempFn();
  11. if(propertiesObject){
  12. Object.defineProperties(tempObj, propertiesObject);
  13. }
  14. return tempObj;
  15. }

算法

map

image.png
image.png
image.png
image.png
image.png
image.png

每日一题

CV了一份 二分查找

富文本编辑器