aboutsummaryrefslogtreecommitdiff
path: root/src/utils/merge-locales.ts
blob: 17683a3aaa539477eee264d5725dffc867c7a34e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import type { LocaleDefinition } from '..';

/**
 * Merges the given locales into one locale.
 * The locales are merged in the order they are given.
 * The first locale that provides an entry for a category will be used for that.
 * Mutating the category entries in the returned locale will also mutate the entries in the respective source locale.
 *
 * @param locales The locales to merge.
 *
 * @returns The newly merged locale.
 *
 * @example
 * import { de_CH, de, en, mergeLocales } from '@faker-js/faker';
 *
 * const de_CH_with_fallbacks = mergeLocales([ de_CH, de, en ]);
 *
 * @since 8.0.0
 */
export function mergeLocales(locales: LocaleDefinition[]): LocaleDefinition {
  const merged: LocaleDefinition = {};

  for (const locale of locales) {
    for (const key in locale) {
      const value = locale[key];
      if (merged[key] === undefined) {
        merged[key] = { ...value };
      } else {
        merged[key] = { ...value, ...merged[key] };
      }
    }
  }

  return merged;
}