Skip to content

Instantly share code, notes, and snippets.

@bdadam
Created July 5, 2021 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bdadam/d14672e5ad4245b44c9b6816f39ec040 to your computer and use it in GitHub Desktop.
Save bdadam/d14672e5ad4245b44c9b6816f39ec040 to your computer and use it in GitHub Desktop.
String interpolation
import interpolate from './interpolate';
describe('Interpolate for Translations', () => {
// eslint-disable-next-line jest/no-commented-out-tests
// it('blah', () => {
// expect(interpolate('asdf')).toEqual('asdf');
// expect(interpolate('Hello {0}', ['World!'])).toEqual('Hello World!');
// expect(interpolate('Hello {0} {0}', ['World!'])).toEqual('Hello World! World!');
// expect(interpolate('Hello {0} {1} {2}!', ['World!', 'Welcome', 'here'])).toEqual('Hello World! Welcome here!');
// expect(interpolate('Hello {0} {1} {2}! {1} {2}!', ['World!', 'Welcome', 'here'])).toEqual(
// 'Hello World! Welcome here! Welcome here!',
// );
// expect(interpolate('Hello {name}!', { name: 'Adam' })).toEqual('Hello Adam!');
// expect(interpolate('Hello {name} {name}!', { name: 'Adam' })).toEqual('Hello Adam Adam!');
// expect(interpolate('Hello {name}! Welcome {location}!', { name: 'Adam', location: 'here' })).toEqual(
// 'Hello Adam! Welcome here!',
// );
// });
it('blah', () => {
expect(interpolate('asdf')).toEqual('asdf');
expect(interpolate('Hello {0}', 'World!')).toEqual('Hello World!');
expect(interpolate('Hello {0} {0}', 'World!')).toEqual('Hello World! World!');
expect(interpolate('Hello {0} {1} {2}!', 'World!', 'Welcome', 'here')).toEqual('Hello World! Welcome here!');
expect(interpolate('Hello {0} {1} {2}! {1} {2}!', 'World!', 'Welcome', 'here')).toEqual(
'Hello World! Welcome here! Welcome here!',
);
expect(interpolate('Hello {name}!', { name: 'Adam' })).toEqual('Hello Adam!');
expect(interpolate('Hello {name} {name}!', { name: 'Adam' })).toEqual('Hello Adam Adam!');
expect(interpolate('Hello {name}! Welcome {location}!', { name: 'Adam', location: 'here' })).toEqual(
'Hello Adam! Welcome here!',
);
});
});
function interpolate(str: string, ...args: [Record<string, string | number>] | Array<string | number>): string {
if (args.length === 0) {
return str;
}
if (args.length === 1 && typeof args[0] === 'object') {
const obj = args[0] as Record<string, string | number>;
return Object.keys(obj).reduce((acc, current) => {
return acc.replace(new RegExp(`\\{${current}\\}`, 'g'), `${obj[current]}`);
}, str);
}
const values = args as Array<string | number>;
return values.reduce((acc: string, current, idx) => {
return acc.replace(new RegExp(`\\{${idx}\\}`, 'g'), `${current}`);
}, str);
}
export default interpolate;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment