aboutsummaryrefslogtreecommitdiff
path: root/src/utils
diff options
context:
space:
mode:
Diffstat (limited to 'src/utils')
-rw-r--r--src/utils/merge-locales.ts37
1 files changed, 37 insertions, 0 deletions
diff --git a/src/utils/merge-locales.ts b/src/utils/merge-locales.ts
new file mode 100644
index 00000000..f5149306
--- /dev/null
+++ b/src/utils/merge-locales.ts
@@ -0,0 +1,37 @@
+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
+ * const de_CH_with_fallbacks = mergeLocales([ de_CH, de, en ]);
+ */
+export function mergeLocales(locales: LocaleDefinition[]): LocaleDefinition {
+ const merged: LocaleDefinition = {} as LocaleDefinition;
+
+ for (const locale of locales) {
+ for (const key in locale) {
+ if (merged[key] === undefined) {
+ if (typeof locale[key] === 'object') {
+ merged[key] = { ...locale[key] };
+ } else {
+ merged[key] = locale[key];
+ }
+ } else {
+ if (typeof locale[key] === 'object') {
+ merged[key] = { ...locale[key], ...merged[key] };
+ } else {
+ // Primitive values cannot be merged
+ }
+ }
+ }
+ }
+
+ return merged;
+}