mkdir demo
cd demo
npm init
npm install -g babel
npm install -g babel-cli
npm install --save-dev babel-preset-es2015-node5
在项目目录创建两个文件夹 functional-playground 和lib
mkdir functional-playground
mkdir lib
在lib目录下创建文件 es6-functional.js
const forEach = (array, fn) => {
let i;
for (i = 0; i < array.length; i++)
fn(array[i])
}
export default forEach
在functional-playground目录下创建文件play.js
import forEach from '../lib/es6-functional'
var array = [1, 2, 3]
forEach(array, (data) => console.log(data))
执行命令
babel-node functional-playground/play.js --presets es2015-node5
执行结果如下
也可以将上述脚本写到package.json中
执行 npm run playground 命令可以查看到一样的结果
在es6-functional.js中定义更多的抽象函数
const forEach = (array, fn) => {
let i;
for (i = 0; i < array.length; i++)
fn(array[i])
}
const forEachObject = (obj, fn) => {
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
fn(property, obj[property])
}
}
}
const unless = (predicate, fn) => {
if (!predicate)
fn()
}
export {
forEach,
forEachObject,
unless
}
在 play.js 调用
import {
forEach,
forEachObject,
unless
} from '../lib/es6-functional'
var array = [1, 2, 3]
forEach(array, (data) => console.log(data))
let object = {
a: 1,
b: 2
}
forEachObject(object, (k, v) => console.log(k + ":" + v))
forEach([1, 2, 3, 4, 5, 6, 7], (number) => {
unless((number % 2), () => {
console.log(number, " is even")
})
})
执行 npm run playground 命令 查看结果