getter源码解读
var REG_KEY = /\[(['"_a-zA-Z0-9]*)\]|\./gi;/*** getter* @param {object} data the object data* @param {string} path the key path you want to get* @param {object} options another options*/function getter(data, path) {// 处理是不是有第三个参数var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};// 这里使用这个正则 让path由字符串转为 [],调用这个正则会使数组中出现 undefined(搞不懂为什么这么处理);// 如 data为{a:{b:{c:c}}}, path为'a.b.c' ==> 此处path.split(REG_KEY)返回的是[a,undefined,b,undefined,c];// 然后经 filter 处理后 pathArr为[a,b,c]var pathArr = path.split(REG_KEY).filter(function (item) {return !!item;});var result = pathArr.reduce(function (result, currentPath, currentIndex) {// 如果 当前遍历的第一项有不为 null 的 errorPath,则继续进行if (!result.errorPath) {// get value// 将 currentPath([a,b,c]中的每一项)中的 ' 或 "通过正则去掉;var key = currentPath.replace(/[\'\"]/gi, '');// 给当前项的 value 重新赋值,从而实现一层一层的验证 正确性result.value = result.value[key];// check value// 通过 currentIndex !== pathArr.length - 1 判断是不是最后一项,是的话,说明data没问题,不走下面逻辑if (currentIndex !== pathArr.length - 1) {// can not get the next valuevar currentValueType = Object.prototype.toString.call(result.value);// 此方法只支持 数组 和对象,如果有一层为 字符串、数字、布尔、null、undefined则应该抛错if (/String|Number|Boolean|Null|Undefined/.test(currentValueType)) {result.errorPath = currentPath;}}}return result;// { value: data, errorPath: null } 为reduce 中的第一项,即为我们要验证的 那个 data({a:{b:{c:'c'}}})}, { value: data, errorPath: null });// throw errorif (options.errorCallback && Object.prototype.toString.call(options.errorCallback) === '[object Function]') {options.errorCallback(result.errorPath, pathArr);}return result.value;}
注: !!item —> 将!!右边的值 转化为 布尔值
// 柯理化前const get = (p, o) =>p.reduce((xs, x) =>(xs && xs[x]) ? xs[x] : null, o)// 柯理化后const get = p => o =>p.reduce((xs, x) =>(xs && xs[x]) ? xs[x] : null, o)
柯理化的好处:
const getUserComments = get(['user', 'posts', 0, 'comments'])console.log(getUserComments(props))// [ 'Good one!', 'Interesting...' ]console.log(getUserComments({user:{posts: []}}))// null
