javascript - 如何改进或优化这段代码
问题描述
如何改进或优化此代码。虽然它给出了所需的结果。我想用更好的方法来写它。
我正在从 www.contentful.com 获取数据,然后对其进行过滤以使用其密钥进行本地化。注意我们必须使用 .reduce() 函数,这是一个要求
import * as fs from 'fs';
const client = createClient();
interface IEntry {
id: string;
text: string;
}
interface IEntries {
[key: string]: { [key: string]: string };
}
export async function getLocalization() {
const entries = await client.getEntries<IEntry>({
skip: 0,
limit: 100,
locale: '*',
content_type: 'translation',
});
let enEntries: IEntries = entries.items
.map((e: any) => e.fields)
.reduce(
(ret, entry) => ({
...ret,
[entry.id.fi]: entry.text.en,
}),
{},
);
let fiEntries: IEntries = entries.items
.map((e: any) => e.fields)
.reduce(
(ret, entry) => ({
...ret,
[entry.id.fi]: entry.text.fi,
}),
{},
);
let svEntries: IEntries = entries.items
.map((e: any) => e.fields)
.reduce(
(ret, entry) => ({
...ret,
[entry.id.fi]: entry.text.sv,
}),
{},
);
const translations = {
['en']: { ...enEntries },
['fi']: { ...fiEntries },
['sv']: { ...svEntries },
};
const dir = './data';
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
fs.writeFileSync('data/translations.json', JSON.stringify(translations));
return true;
}
getLocalization();
Output can be found on this link (actual values have been removed): https://imgur.com/k3rzxWx
解决方案
我认为在这种情况下,以下方法将是最好的。
import { IFields, ITranslation } from './localization.types';
import * as fs from 'fs';
const client = createClient();
const en: ITranslation = {};
const fi: ITranslation = {};
const sv: ITranslation = {};
export async function getLocalization() {
const entries = await client.getEntries<IFields>({
skip: 0,
limit: 100,
locale: '*',
content_type: 'translation',
});
const localizations = entries.items
.map(e => e.fields)
.reduce(
(ret, entry) => {
ret.en[entry.id.fi] = entry.text.en === undefined ? 'no_value_found' : entry.text.en;
ret.fi[entry.id.fi] = entry.text.fi === undefined ? 'no_value_found' : entry.text.fi;
ret.sv[entry.id.fi] = entry.text.sv === undefined ? 'no_value_found' : entry.text.sv;
return ret;
},
{ en, fi, sv },
);
const dir = './data';
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
fs.writeFileSync('data/translations.json', JSON.stringify(localizations));
return true;
}
getLocalization();
以下是类型
export interface IId {
fi: string;
}
export interface IText {
en: string;
fi: string;
sv: string;
}
export interface IFields {
id: IId;
text: IText;
}
export interface ITranslation {
[key: string]: string;
}
推荐阅读
- java - Firebase 数据库没有显示图片
- javascript - 访问尚未渲染的 React 组件的 props
- php - 从解码 Json 数组中的键获取值?
- python - Gensim 框架:保存和存储 word2vec 键控向量
- mysql - 带有 GROUP_CONCAT 选项的 MYSQL 查询
- c++ - 用户定义类型的 std::format?
- java - 对整数进行升序和降序排序
- xamarin - 如何将条目(来自登录)绑定到 xamarin 中的 masterdetailpage
- c++ - 标准输出的命令行重定向也应该总是重定向 cout 吗?
- html - 博客上的下拉导航栏不起作用