Node对ES6 语法的支持 【v6.14.4 之后】
- https://node.green/
- https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_6_support_in_Mozilla
- http://es6.ruanyifeng.com/#docs/intro
let、const
let debugId = 1000
const Compiler = require('./Compiler')
模板字符串(字符串的简洁用法,可内嵌函数与变量)
let message = `* ${m.identifier()}`
const ma = `${a.message}`
箭头函数
const exportPlugins = (obj, mappings) => {}
解构赋值
// 从 tapable 模块对象中提取 SyncHook 函数
const { SyncHook } = require('tapable')
rest 参数与扩展运算符
// 多余参数转成一个数组 args[]
function(name, ...args) {
// 把数组以 ... 扩展为参数
this.hooks[name.replace(/**/)].call(...args)
}
Symbol 对象
// 原始数据对象
// 接收参数(可选)来生成一个独一无二的值
const MAYBEEND = Symbol('maybeEnd')
const WRITING = Symbol('writing')
Set 对象
【一种数据结构,可存任意数据类型,且保证值唯一】
// 可接收一个可迭代对象作为参数,构造一个新的 Set 对象
const queue = new Set(this.groupsIterable)
// 可接收空参数生成一个 Set 对象
const chunksProcessed = new Set()
Map 对象
【哈希结构的键值对集合】
// 创建一个空集合,交给 fileTimestamps
const fileTs = (compiler.fileTimestamps = new Map())
Promise 对象
【管理异步状态的对象,在某个时刻来回调返回异步执行结果】
// fs 模块读出文件内容并转成 JSON
// 把整个异步过程包装成一个 Promise 返回
return new Promise((resolve, reject) => {
require('fs').readFile(filename, (err, content) => {
try {
var update = JSON.parse(content)
} catch (e) {
return reject(e)
}
resolve(update)
})
})
for ... of 循环
【遍历循环所有成员】
// 遍历拿到所有该模块的依赖项
for (const dependency of module.dependencies) {}
- Class/Async Function/Generator Function
龟兔赛跑动画
// 声明 2 个比赛队员
const rabbit = '兔子'
const turtle = '乌龟'
// 声明一坨变量,作为赛道起点终点字符串
const start = '|'
const end = '》'
// 赛道上一米一米的距离,用 . 表示
const pad = '.'
// 速度是 1 米/150 毫秒
const speed = 1
// 赛道一共有 50 米
const steps = 50
// 约定兔子在 42 米的时候停下
const stopAt = 42
// 判断兔子是否停下
let stoped = false
// 默认从 0 开始轮询
let t = 0
// 一个定时器的句柄而已
let timer
// 计算兔子距离终点
const getRabbitLastSteps = () => {
return steps - t * speed - t * speed * 3
}
// 计算乌龟距离终点
const getTurtleLastSteps = () => {
return steps - t * speed
}
// 初始赛道状态
const checkRaceInitState = () => {
return `${rabbit}${turtle}${start}${pad.repeat(steps)}${end}`
}
// 兔子领先时的赛道状态
const checkRaceState = () => {
return `${start}${pad.repeat(t * speed)}${turtle}${pad.repeat(t * speed * 3)}${rabbit}${pad.repeat(getRabbitLastSteps())}${end}`
}
// 分情况计算赛道的实时状态
const checkBackRaceState = () => {
if (getGapSteps() <= 0) {
if (getTurtleLastSteps() === 0) {
return `${start}${pad.repeat(stopAt)}${rabbit}${pad.repeat(steps - stopAt)}${end}${turtle}`
} else {
return `${start}${pad.repeat(stopAt)}${rabbit}${pad.repeat(t * speed - stopAt)}${turtle}${pad.repeat(getTurtleLastSteps())}${end}`
}
} else {
return `${start}${pad.repeat(t * speed)}${turtle}${pad.repeat(getGapSteps())}${rabbit}${pad.repeat(steps - stopAt)}${end}`
}
}
// 等待时间,把定时器包装秤一个 Promise
const wait = (sec) => new Promise(resolve => setTimeout(() => resolve(), sec))
// 可以支持特效刷新的命令行日志模块
const chalkWorker = require('chalk-animation')
const initState = checkRaceInitState()
const racing = chalkWorker.rainbow(initState)
const updateRaceTrack = (state) => {
racing.replace(state)
}
const race = () => {
timer = setInterval(() => {
// 判断是否兔子停下
if (!stoped) {
if (getRabbitLastSteps() <= (steps - stopAt)) {
stoped = true
}
}
if (stoped) {
let state = checkBackRaceState()
updateRaceTrack(state)
if (getTurtleLastSteps() === 0) {
// 乌龟过线后就停止定时器
clearInterval(timer)
return
}
} else {
let state = checkRaceState()
updateRaceTrack(state)
}
t++
}, 150);
}
// 等待 20 秒再开始启动比赛
wait(2000).then(() => {
race()
})
基于ES6的改进
const chalkWorker = require('chalk-animation')
class Race extends Object {
constructor(props = {}) {
super(props)
;[
['rabbit', '兔子'],
['turtle', '乌龟'],
['turtleStep', 0],
['rabbitStep', 0],
['start', '|'],
['end', '》'],
['pad', '.'],
['speed', 1],
['steps', 50],
['stopAt', 42]
].forEach(elem => {
const [key, value] = elem
if (!(key in props)) {
this[key] = value
}
})
}
getRaceTrack () {
const {
start,
pad,
turtle,
turtleStep,
rabbit,
rabbitStep,
steps,
end
} = this
if (!turtleStep && !rabbitStep) {
return `${turtle}${rabbit}${start}${pad.repeat(steps)}${end}`
}
const [
[minStr, min],
[maxStr, max]
] = [
[turtle, turtleStep],
[rabbit, rabbitStep]
].sort((a, b) => a[1] - b[1])
const prefix = `${pad.repeat((min || 1) - 1)}`
const middle = `${pad.repeat(max - min)}`
const suffix = `${pad.repeat(steps - max)}`
const _start = `${start}${prefix}${minStr}`
const _end = suffix ? `${maxStr}${suffix}${end}` : `${end}${maxStr}`
return `${_start}${middle}${_end}`
}
updateRaceTrack (state, racing) {
racing.replace(state)
}
updateSteps () {
if (this.turtleStep >= this.steps) return
if (this.rabbitStep <= this.stopAt) {
this.rabbitStep += 3 * this.speed
}
this.turtleStep += 1 * this.speed
}
race () {
const initState = this.getRaceTrack()
const racing = chalkWorker.rainbow(initState)
let t = 0
let timer = setInterval(() => {
if (t <= 6) {
t += 1
return
}
const state = this.getRaceTrack()
this.updateRaceTrack(state, racing)
this.updateSteps()
}, 150)
}
}
const proxy = new Proxy(Race, {
apply (target, ctx, args) {
const race = new target(...args)
return race.race()
}
})
proxy()
网友评论