mirror of
https://github.com/zoriya/v10.git
synced 2026-08-16 02:45:09 +00:00
feat(i18n): convert to opaque keys (#1848)
This commit is contained in:
@@ -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,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' });
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user