Skip to content

Instantly share code, notes, and snippets.

@jacopotarantino
Created October 17, 2018 18:37
Show Gist options
  • Save jacopotarantino/33c2462ce9539cfbea9803d4b00469f2 to your computer and use it in GitHub Desktop.
Save jacopotarantino/33c2462ce9539cfbea9803d4b00469f2 to your computer and use it in GitHub Desktop.
Proxying to an i18n function in order to treat it like an object.
// assume this is our original translate function
const translate = (key) => {
return key.split('.').reduce((acc, current) => {
return acc[current];
}, english);
}
// an example of a dictionary of i18n strings with nested properties
const english = {
foo: {
bar: {
baz: 'bob'
}
}
};
// normally we would just return target[key] but this approach allows us to handle nested properties
const validator = {
get(target, key) {
if (typeof target[key] === 'object' && target[key] !== null) {
return new Proxy(target[key], validator)
} else {
return translate(key);
}
}
};
// this is what we want to export.
const t = new Proxy(translate, validator);
/*
Usage:
import t from 'translate';
const render = () => <p>{t.foo.bar}</p>;
******
works as a function AND as an object!
t.foo.bar.baz === t('foo.bar.baz'); //=> true
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment