Created
September 19, 2019 02:05
-
-
Save guiqide/86bab2f8b3dec2a37256e876a7142260 to your computer and use it in GitHub Desktop.
国际化测试题
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Intl { | |
constructor(set) { | |
this.set = set | |
} | |
get(keyStr) { | |
const keys = keyStr.split('.') | |
let value = this.set | |
for (let i = 0; i < keys.length; i++) { | |
if (value[keys[i]]) { | |
value = value[keys[i]] | |
} else { | |
this.value = null | |
return null | |
} | |
} | |
this.value = value | |
return value | |
} | |
transform() { | |
const arr = arguments | |
return this.value.replace(/\{(\d+)\}/g, function(s0, s1) { | |
if (s1 === '') { | |
return null | |
} | |
return arr[s1] | |
}) | |
} | |
} | |
/** | |
* 题目:实现一个国际化intl()方法,支持传入需要获取文案的key和文案集合。在集合中获取不到的key就返回key本身,文案中支持字符串替换。请结合国际化场景尽可能的完善该方法的功能和扩展性。 | |
* @param {string} key 属性,如果传错则函数返回key本身 | |
* @param {object} set 用来初始化不同种类的文案 | |
* @param {array} arr 可不传,如果不传,则直接返回;如果传则会替换"{}"中的内容 | |
*/ | |
function intlHandler(key, set, arr) { | |
const intl = new Intl(set) | |
data = intl.get(key) | |
if (!data) { | |
return key | |
} | |
if (arr) { | |
return intl.transform(...arr) | |
} | |
return data | |
} | |
// demo1, 取消注释可查看 | |
// const result = intlHandler('zh.date', { | |
// zh: { | |
// date: '{0}年{1}月{2}日' | |
// }, | |
// en: { | |
// date: '{0}-{1}-{2}' | |
// } | |
// }) | |
// demo2 | |
const result = intlHandler('zh.date', { | |
zh: { | |
date: '{0}年{1}月{2}日' | |
}, | |
en: { | |
date: '{0}-{1}-{2}' | |
} | |
}, ['二零一九', '九', '十八']) | |
console.log(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment