zoukankan      html  css  js  c++  java
  • 手写lodash.get

    1.简单版

    /**
     * @param {object} source
     * @param {string | string[]} path
     * @param {any} [defaultValue]
     * @return {any}
     */
    function get(source, path, defaultValue = undefined) {
     if(typeof object !== 'object') {
      return defaultValue
     }
     if(Array.isArray(path) && !path.length) {
        return defaultValue
      }
      if(typeof path === "string" && !path.trim().length) {
        return defaultValue
      }
      const paths = Array.isArray(path) ? path : path.replace(/[/g, '.').replace(/]/g, '').split('.');
      return paths.reduce((cur, pre) => (cur || {})[pre], source) || defaultValue;
    }
    

      

      

      

    2.完整版

    function isDef(target) {
      return target !== undefined && target !== null;
    }
    
    function nextSplit(key) {
      const cartfulIndexs = [];
      const regx = /[(d+)]/g;
      let wholeKey = key;
      let matchResult;
      while ((matchResult = regx.exec(key))) {
        cartfulIndexs.push(matchResult[1]);
      }
      if (cartfulIndexs.length) {
        wholeKey = wholeKey.substring(0, wholeKey.indexOf(cartfulIndexs[0]) - 1);
      }
      return [wholeKey, ...cartfulIndexs];
    }
    
    export function get(target, keyStrs, defaultValue) {
      if (!isDef(target)) return defaultValue;
    
      const keyParts = keyStrs
        .split(".")
        .map(nextSplit)
        .flat();
    
      let value = target;
    
      for (let index = 0; index < keyParts.length; index++) {
        const key = keyParts[index];
        // console.log(key, value);
        if (isDef(value[key])) {
          value = value[key];
        } else {
          return defaultValue;
        }
      }
      return value;
    }
    

      

      

  • 相关阅读:
    程序员代码面试指南:IT名企算法与数据结构题目最优解
    经典排序算法
    Log4j输出格式控制--log4j的PatternLayout参数含义
    常用数据库4 mongodb
    常用数据库2 sqlite及SQL注入
    面试常问-数据库索引实现原理
    自定义web框架
    HTML|CSS之布局相关总结
    C++模板类练习题
    C++中的运算符重载练习题
  • 原文地址:https://www.cnblogs.com/ygunoil/p/15232592.html
Copyright © 2011-2022 走看看