wip(i18n): 优化获取对象中指定路径值的性能

pull/2745/head
sight 2025-06-27 16:20:03 +08:00
parent e893e9617b
commit 25be3c9736
1 changed files with 34 additions and 7 deletions

View File

@ -197,10 +197,11 @@ layui.define('lay', function(exports) {
var INDEX_REPLACE_REGEX = /\{(\d+)\}/g;
/**
* 获取对象中的值lodash _.get 简易版
* @param {Record<string, any>} obj
* @param {string} path
* @param {any} defaultValue
* 获取对象中指定路径的值类似于 lodash _.get 方法简易版
* @param {Record<string, any>} obj - 要查找的对象
* @param {string} path - 要查找的路径支持类似 'a[0].b.c' 的格式
* @param {any} defaultValue - 若未找到对应值时返回的默认值
* @returns {any} - 找到的值或默认值
*/
function get(obj, path, defaultValue) {
// 'a[0].b.c' ==> ['a', '0', 'b', 'c']
@ -217,6 +218,27 @@ layui.define('lay', function(exports) {
return result;
}
/**
* 为纯函数创建具有缓存功能的版本类似于 lodash _.memoize 方法简易版
* @template T
* @param {(key: string, ...args) => T} fn - 需要缓存的函数第一个参数为键
* @returns {{(key: string, ...args): T, cleanup: () => void}} - 带有缓存的函数
*/
function memoize(fn){
/** @type Record<string, T> */
var cache = Object.create(null);
function cachedFn(key) {
var hit = cache[key];
return hit || (cache[key] = fn.apply(cache, arguments));
}
cachedFn.cleanup = function() {
cache = Object.create(null);
}
return cachedFn;
}
/**
* 对传入的值进行转义处理
* 若值为字符串直接进行转义若为函数对函数返回的字符串进行转义若为数组对数组中的字符串元素进行转义
@ -245,9 +267,14 @@ layui.define('lay', function(exports) {
config: config,
set: function(options) {
lay.extend(config, options);
getCachedValueForKeyPath.cleanup();
}
};
var getCachedValueForKeyPath = memoize(function(key, obj){
return get(obj, key, key);
});
/**
* 根据给定的键从国际化消息中获取翻译后的内容
* 未文档化的私有方法仅限内部使用
@ -281,14 +308,14 @@ layui.define('lay', function(exports) {
i18n.translation = function(key) {
var options = config;
var args = arguments;
var i18nMessage = options.messages[options.locale];
var i18nMessages = options.messages[options.locale];
if (!i18nMessage) {
if (!i18nMessages) {
hint.error('Locale "' + options.locale + '" not found. Please add i18n messages for this locale first.', 'warn');
return key;
}
var result = get(i18nMessage, key, key);
var result = getCachedValueForKeyPath(key, i18nMessages);
// 替换占位符
if (typeof result === 'string' && args.length > 1) {