当前位置:网站首页>"Source code interpretation" famous programmer TJ's only library
"Source code interpretation" famous programmer TJ's only library
2022-07-05 07:34:00 【Front end watermelon brother_】
Hello everyone , I'm brother watermelon . I recently tried to open a series of source code interpretation , Interpret some simple or complex source code from time to time .
Today I want to interpret npm Third party library source code :only, Warehouse address is :https://github.com/tj/node-only
This library is tj Tools and methods written by great God .tj God is a programmer boss , Mainly in the nodejs The field has made many open source contributions , yes Express、Koa、node-canvas And the creators and contributors of a series of well-known open source projects .
only What can the method do ?
only Its function is very simple : Return the whitelist attribute of an object . To be specific , It is to extract some attributes of the specified object and put them into the new object , And return this new object .
const only = require('only');
var obj = {
name: 'tobi',
last: 'holowaychuk',
email: '[email protected]',
_id: '12345'
};
only(obj, 'name last email');
/* { name: 'tobi', last: 'holowaychuk', email: '[email protected]' } */
only Method requires an object to be passed in , And a white list , This list can be an array of attribute names , It can also be a string represented by a space spaced attribute name .
The second parameter supports string format , Because it is more convenient to use , Can write a lot less quotation marks . Elegance in use , It's our design API It needs to be considered .
only The implementation of the library
module.exports = function(obj, keys){
obj = obj || {
};
if ('string' == typeof keys) keys = keys.split(/ +/);
return keys.reduce(function(ret, key){
if (null == obj[key]) return ret;
ret[key] = obj[key];
return ret;
}, {
});
};
Code reading
First, for the first parameter obj Simple fault tolerance . If obj Is a value of undefined or null False values like , We set it as an empty object , Prevent throwing errors .
Then it is possible to convert the white list in the form of string into the format of array .
The method used is :keys.split(/ +/), It's used here split Regular expression parameter writing method ,/ +/ This regular expression represents a number greater than or equal to 1 Multiple space characters of . This is actually a very common way to split strings and get arrays .
Finally, use what Lao Niao likes very much Array.prototype.reduce() Writing , Come on keys Iterating through arrays .
For each key, As long as the original array is not null or undefined, Just copy it to the new object .
reduce() The return value of the method is the new object we want , Return it directly to .
Let's talk about why some senior front-end like to use reduce() Method . Because reduce This method is compared with forEach、map These methods should be more flexible , It can return any type of value without losing brevity . forEach no return value , and map Only arrays of the same size of array type can be returned , Although it conforms to the principle of single responsibility , But it also loses flexibility .
I once wrote an article about reduce The article , If you are interested, you can have a look : Why do we say array instances reduce The method is flexible ?
only The method is interpreted .
边栏推荐
- Basic series of SHEL script (III) for while loop
- Apple terminal skills
- Raspberry pie 4B arm platform aarch64 PIP installation pytorch
- Jenkins reported an error. Illegal character: '\ufeff'. Class, interface or enum are required
- Use of Pai platform
- Idea to view the source code of jar package and some shortcut keys (necessary for reading the source code)
- Target detection series - detailed explanation of the principle of fast r-cnn
- How can Oracle SQL statements modify fields that are not allowed to be null to allow nulls?
- Simple operation of running water lamp (keil5)
- Intelligent target detection 59 -- detailed explanation of pytoch focal loss and its implementation in yolov4
猜你喜欢

DelayQueue延迟队列的使用和场景

The folder directly enters CMD mode, with the same folder location

M2dgr slam data set of multi-source and multi scene ground robot

DataGrid offline installation of database driver

QT small case "addition calculator"
![[vscode] prohibit the pylance plug-in from automatically adding import](/img/a7/d96c0c4739ff68356c15bafbbb1328.jpg)
[vscode] prohibit the pylance plug-in from automatically adding import

Play with grpc - go deep into concepts and principles

Differences between pycharm and idle and process -- join() in vs Code

Ugnx12.0 initialization crash, initialization error (-15)

Rough notes of C language (2) -- constants
随机推荐
Simple operation of nixie tube (keil5)
氢氧化钠是什么?
GBK error in web page Chinese display (print, etc.), solution
Chapter 2: try to implement a simple bean container
Apple input method optimization
The mutual realization of C L stack and queue in I
(tool use) how to make the system automatically match and associate to database fields by importing MySQL from idea and writing SQL statements
Idea push project to code cloud
I 用c l 栈与队列的相互实现
第 2 章:小试牛刀,实现一个简单的Bean容器
Idea to view the source code of jar package and some shortcut keys (necessary for reading the source code)
【idea】Could not autowire. No beans of xxx type found
I 用c I 实现队列
Apple system shortcut key usage
M2DGR 多源多场景 地面机器人SLAM数据集
611. 有效三角形的个数
[idea] common shortcut keys
Ethtool principle introduction and troubleshooting ideas for network card packet loss (with ethtool source code download)
Import CV2 prompt importerror: libgl so. 1: Cannot open shared object file: no such file or directory
Machine learning Seaborn visualization