Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(localize): added MessageFormatLite #356

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions packages/localize/src/MessageFormatLite.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* Very lightweight message formatter.
* It supports 'key replacement' formatting
*/
export class MessageFormatLite {
constructor(message) {
this.message = message;
}

/**
* @desc key replacement formatter (supports nested keys)
* - from:
* - message: 'replace {key} to {obj.k}'
* - vars: {key: 'val' obj: {k: 'nestedVal'}}
* - to: 'replace val to nestedVal'
* @param {object} vars key value map of variables to be replaced
*/
format(vars) {
if (!vars) {
return this.message;
}
let result = this.message;
const varsKeys = Object.keys(vars);
const messageKeys = this.message.match(/\{.*?\}/gm) || []; // gets ['{key}', '{obj.k}']
messageKeys.forEach(keyWithAccolades => {
const k = keyWithAccolades.slice(1, -1);
if (varsKeys.includes(k)) {
// if '{key}'
result = result.replace(`${keyWithAccolades}`, vars[k]);
} else if (k.includes('.')) {
// if '{obj.k}'
const pathKeys = k.split('.');
const /** @type {string} */ replacement = pathKeys.reduce((res, acc) => res[acc], vars);
result = result.replace(`${keyWithAccolades}`, replacement);
}
});
return result;
}
}