Skip to main content

Awesome Code Snippet

· 2 min read
Alan

收藏一些比较惊艳的代码片段

JavaScript

模板字符串替换

/**
* format string
* @example
* "Hello {fn}. My full name is {my}.".templ({fn:"Alan", ln:"Wei", my:function(){return this.fn + " " + this.ln;}});
* "Hello Alan. My full name is Alan Wei."
*
* */
String.prototype.templ = function (json) {
var args = arguments;
var paras = Array.prototype.splice.call(args, 1, args.length - 1);

var fnReg = /\{\{([\w\s\+\.\(\)'\-";]+)\}\}/g;
var fnText = this.replace(fnReg, function (g0, g1) {
var innerFunction = new Function(g1);
return innerFunction.apply(json, paras);
});

var placeHoldReg = /\{(\w+|\d*|_*)\}/g;
return fnText.replace(placeHoldReg, function (g0, g1) {
var value = json[g1];
return typeof (value) === "function" ? value.apply(json, paras) : value;
});
};

迭代指定目录和文件

const path = require("path");
const fs = require("fs");

/**
* 迭代目录
* @param {string} root 根目录
* @returns {ArrayLike<{path: string, relative: string, state: fs.Stats}>}
*/
function* ioRecursive(root) {
yield* (function* foreach(dir) {
for (let item of fs.readdirSync(dir, { encoding: "utf-8" })) {
const fullPath = path.join(dir, item);
const state = fs.statSync(fullPath);

yield {
path: fullPath,
relative: path.relative(root, fullPath),
state: state
};

if (state.isDirectory()) {
yield* foreach(fullPath);
}
}
})(root);
}