Skip to content

Instantly share code, notes, and snippets.

@thinhbuzz
Last active April 20, 2020 19:44
Show Gist options
  • Save thinhbuzz/0c04e1c70045283ceca91719a0bd7d3e to your computer and use it in GitHub Desktop.
Save thinhbuzz/0c04e1c70045283ceca91719a0bd7d3e to your computer and use it in GitHub Desktop.
simple template function
export function isFunction(arg) {
return typeof arg === 'function';
}
const cachedKeys = new Map();
/**
* Get data by key
* const data = {age: {value: 9}};
* getData(data, 'age.value') => 9
* getData(data, 'age.buzz') => 'age.buzz'
*
* @param {object} data
* @param {string} originKey
* @returns {string}
*/
function getData(data, originKey) {
if (typeof data !== 'object') {
return originKey;
}
const keys = cachedKeys.get(originKey) || originKey.replace(/([^a-zA-Z_.]+)/g, '').split('.');
let result = originKey;
for (const key of keys) {
if (key in data) {
result = data[key];
data = data[key];
continue;
}
result = originKey;
break;
}
return isFunction(result) ? result() : result;
}
/**
* Simple template string
*
* @example
*
* const str = 'My name is ${name}, and is ${age}, ${girlName} is my girl friend';
* const data = {name: 'Buzz', age: 'young man'};
* // result = 'My name is Buzz, and is young man, ${girlName} is my girl friend';
*
* @param {string} str
* @param {object} params
* @returns {string}
*/
export function template(str, params) {
if (!params) { // falsy value
return str;
}
return str.replace(/\${([a-zA-Z_.]+)}/g, (substring) => getData(params, substring));
}
export function isFunction(arg: any): arg is Function {
return typeof arg === 'function';
}
const cachedKeys: Map<string, string> = new Map();
/**
* Get data by key
* const data = {age: {value: 9}};
* getData(data, 'age.value') => 9
* getData(data, 'age.buzz') => 'age.buzz'
*
* @param {object} data
* @param {string} originKey
* @returns {string}
*/
function getData(data: any, originKey: string): string {
if (typeof data !== 'object') {
return originKey;
}
const keys = cachedKeys.get(originKey) || originKey.replace(/([^a-zA-Z_.]+)/g, '').split('.');
let result: string | Function = originKey;
for (const key of keys) {
if (key in data) {
result = data[key];
data = data[key];
continue;
}
result = originKey;
break;
}
return isFunction(result) ? result() : result;
}
/**
* Simple template string
*
* @example
*
* const str = 'My name is ${name}, and is ${age}, ${girlName} is my girl friend';
* const data = {name: 'Buzz', age: 'young man'};
* // result = 'My name is Buzz, and is young man, ${girlName} is my girl friend';
*
* @param {string} str
* @param {object} params
* @returns {string}
*/
export function template(str: string, params: any): string {
if (!params) { // falsy value
return str;
}
return str.replace(/\${([a-zA-Z_.]+)}/g, (substring: string) => getData(params, substring));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment