feat(i18n): convert to opaque keys (#1848)

This commit is contained in:
Sam Potts
2026-07-28 16:46:25 +10:00
committed by GitHub
parent be89470447
commit a3e673bd68
221 changed files with 7040 additions and 4307 deletions
+33
View File
@@ -0,0 +1,33 @@
/**
* Flattens nested object values into dot-separated keys.
*
* @param object - The object to flatten.
* @param options - Options controlling the flattened key path.
* @returns A new object containing the flattened values.
*
* @example
* ```ts
* flatten({ buttons: { play: 'Play' } });
* // { 'buttons.play': 'Play' }
* ```
*/
export interface FlattenOptions {
prefix?: string;
}
export function flatten(object: Record<string, unknown>, options: FlattenOptions = {}): Record<string, unknown> {
const { prefix = '' } = options;
const result: Record<string, unknown> = {};
for (const [key, value] of Object.entries(object)) {
const fullKey = prefix ? `${prefix}.${key}` : key;
if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
Object.assign(result, flatten(value as Record<string, unknown>, { prefix: fullKey }));
} else {
result[fullKey] = value;
}
}
return result;
}
+1
View File
@@ -1,5 +1,6 @@
export { deepEqual } from './deep-equal';
export { defaults } from './defaults';
export { type FlattenOptions, flatten } from './flatten';
export { omit } from './omit';
export { pick } from './pick';
export { shallowEqual } from './shallow-equal';
@@ -0,0 +1,29 @@
import { describe, expect, it } from 'vitest';
import { flatten } from '../flatten';
describe('flatten', () => {
it('flattens nested objects into dot-separated keys', () => {
expect(
flatten({
buttons: { play: 'Play', pause: 'Pause' },
common: { empty: '' },
})
).toEqual({
'buttons.play': 'Play',
'buttons.pause': 'Pause',
'common.empty': '',
});
});
it('preserves non-object values as leaves', () => {
expect(flatten({ value: 0, enabled: false, items: ['one'] })).toEqual({
value: 0,
enabled: false,
items: ['one'],
});
});
it('accepts a prefix option', () => {
expect(flatten({ play: 'Play' }, { prefix: 'buttons' })).toEqual({ 'buttons.play': 'Play' });
});
});