首页 > 解决方案 > 如何改进或优化这段代码

问题描述

如何改进或优化此代码。虽然它给出了所需的结果。我想用更好的方法来写它。

我正在从 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

标签: javascripttypescriptlogic

解决方案


我认为在这种情况下,以下方法将是最好的。

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;
}


推荐阅读