- 本文参加了由公众号@若川视野 发起的每周源码共读活动, 点击了解详情一起参与。
- 这是源码共读的第33期,链接:【源码共读】第33期 | arrify 转数组
前言
阅读源码,源码分析,解决技术突破。
源码解析
观察目录结构
安装 package 依赖
npm install
在 package.json 中找到入口文件
由此可见 index.js 是入口文件
export default function arrify(value) {
// 判断参数是否为 空值 或者 未传值
if (value === null || value === undefined) {
return [];
}
// 判断 参数值是否是个数组
if (Array.isArray(value)) {
return value;
}
// 判断参数值是否为 字符串类型
if (typeof value === 'string') {
return [value];
}
// 判断 参数是否是一个可迭代对象 并结构出来
if (typeof value[Symbol.iterator] === 'function') {
return [...value];
}
// 若都不是 则直接带进去
return [value];
}
Symbol.iterator
Symbol.iterator 为每一个对象定义了默认的迭代器。该迭代器可以被 for...of 循环使用。
当需要对一个对象进行迭代时(比如开始用于一个 for..of 循环中),它的 @@iterator 方法都会在不传参情况下被调用,返回的迭代器用于获取要迭代的值。
Symbol.iterator 的属性特性 | |
|---|---|
| 可写 | 否 |
| 可枚举 | 否 |
| 可配置 | 否 |
调试测试用例
根据 package.json 可得测试工具使用的 ava
AVA 是 Node.js 的测试运行器,具有简洁的 API、详细的错误输出、拥抱新的语言特性和进程隔离,让您自信地开发🚀
import test from 'ava';
import arrify from './index.js';
test('main', t => {
// 校验俩者深度值是否不同
t.notDeepEqual(arrify('a'), ['b']);
// 校验俩者深度值是否相同同
t.deepEqual(arrify('a'), ['a']);
// 校验 set对象转化后的 和 数组直接的值是否相同
t.deepEqual(arrify(new Set('a')), ['a']);
});
测试用例
npm run test
运行的时候遇到俩个 错误
- Strings must use singlequote. quotes
- Unexpected parentheses around single function argument. arrow-parens
因为在这里 调试测试文件的时候 我使用的是 prettier 格式化工具然后自动格式化会自动把代码变成双引号和函数必须携带小括号。
在这里 我在根目录创建了一个 .prettierrc 配置文件
{
"singleQuote": true,
"arrowParens": "always"
}
设置好后 默认的 prettier格式化就会变为 单引号和总是去掉小括号
上述报错愿意主要是 该项目使用了 xo 工具导致的
根据 scripts 中得出 test 脚本一共调用了三个命令
第一个先调用的 就是 xo 命令
xo 具有出色默认值的 JavaScript/TypeScript linter(ESLint 包装器)
XO Default code style
Any of these can be overridden if necessary.
- Tab indentation (or space)
- Semicolons (or not)
- Single-quotes
- Trailing comma for multiline statements
- No unused variables
- Space after keyword
if (condition) {} - Always
===instead of==
Check out an example and the ESLint rules.
Default code style
Any of these can be overridden if necessary.
- Tab indentation (or space)
- Semicolons (or not)
- Single-quotes
- Trailing comma for multiline statements
- No unused variables
- Space after keyword
if (condition) {} - Always
===instead of==
Check out an example and the ESLint rules.
翻译下来是这样的
在 xo中默认就是必须为 单引号 和 单参数的
修改完 .prettierrc 后 再次调用 test 就ok了
结语
源码解析与调用测试用例都均已完毕。
收货满满每日进步一点点!