import * as _ from 'lodash'; import {parseExpressString as _parseExpressionString, isExpressionString} from '../parser/index'; import { runTimeType } from '../core/Container/types'; export type compilePairType = { [s: string]: S }; /** * 遍历对象或者数组的所有属性,处理所有找到的ExpressionString, 并返回一个新的解析好的对象 * * @param {T} props 数据对象 * @param {runTimeType} runTime ExpressionString 上下文 * @param {string[]} blackList 变量名黑名单 * @param {boolean} isDeep 是否递归解析 * @param {string[]} whiteList 变量名白名单 * @returns {T} */ export function compileExpressionString(props: T, runTime: runTimeType, blackList: string[] = [], isDeep: boolean = false, whiteList?: string[]): T { let copy = _.clone(props); _.each(copy, (item, key) => { if (blackList.indexOf(key) >= 0) { return; } if (whiteList && _.isArray(whiteList)) { if (whiteList.indexOf(key) < 0) { return; } } if (isExpression(key)) { key = _parseExpressionString(key, runTime); copy[key] = item; } if (typeof item === 'string' && isExpression(item)) { copy[key] = _parseExpressionString(item, runTime); } if (isDeep && (_.isObjectLike(item) || _.isArrayLikeObject(item))) { copy[key] = compileExpressionString(item, runTime, blackList, isDeep, whiteList); } }); return copy; } /** * 判断字符串是否是ExpressionString * @param {string} str 字符串 * @returns {boolean} */ export function isExpression(str: string) { return typeof str === 'string' && isExpressionString(str); } /** * 过滤掉数据中含有ExpressionString的字段 * @param {T} obj * @returns {T} */ export function filterExpressionData(obj: T): T { let copy = _.cloneDeep(obj); function walker(o: Object) { _.each(o, (val, name) => { if (typeof val === 'string' && isExpression(val)) { delete o[name]; } if (_.isObjectLike(val)) { filterExpressionData(val); } }); } walker(copy); return copy; } export function safeStringify(obj: Object) { let cache = new WeakMap(); return JSON.stringify(obj, (key, value) => { if (typeof value === 'object' && value !== null) { if (cache.get(value)) { return; } cache.set(value, true); } return value; }); } export function parseExpressionString(str: string, context: runTimeType) { return _parseExpressionString(str, context); }