Skip to content

Commit

Permalink
lodash => native
Browse files Browse the repository at this point in the history
  • Loading branch information
puzrin committed Dec 2, 2022
1 parent c7b7677 commit b509a1d
Show file tree
Hide file tree
Showing 10 changed files with 44 additions and 63 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ env:
es6: true

parserOptions:
ecmaVersion: '2018'
ecmaVersion: '2020'

rules:
accessor-pairs: 2
Expand Down
3 changes: 1 addition & 2 deletions lib/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

const ArgumentParser = require('argparse').ArgumentParser;
const debug = require('debug')('cli');
const _ = require('lodash');

const commands = [
require('./cmd_extract'),
Expand Down Expand Up @@ -40,7 +39,7 @@ module.exports.run = function (test_cli_params) {
);

c.subparserArgsList.forEach(item => {
let args = [].concat(item.args).concat([ _.cloneDeep(item.options) ]);
let args = [].concat(item.args).concat([ JSON.parse(JSON.stringify(item.options)) ]);
subparser.add_argument(...args);
});
});
Expand Down
14 changes: 7 additions & 7 deletions lib/cmd_compile.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
'use strict';


const _ = require('lodash');
const TranslationKeys = require('./translation_keys');
const AppError = require('./app_error');
const shell = require('shelljs');
Expand Down Expand Up @@ -117,25 +116,26 @@ You did not specified locale and we could not autodetect it. Use '-l' option.

// Pre-fill .singular & plural props for edge case - missed locale
sorted_locales.forEach(l => {
_.set(data, [ l, 'singular' ], {});
_.set(data, [ l, 'plural' ], {});
data[l] = { singular: {}, plural: {} };
});


translationKeys.phrases.forEach(p => {
if (p.value === null) return;

// Singular
if (!_.isPlainObject(p.value)) {
_.set(data, [ p.locale, 'singular', p.key ], p.value);
if (p.value?.constructor !== Object) {
Object.assign(data[p.locale]['singular'], { [p.key]: p.value });
return;
}

// Plural
_.forEach(p.value, (val, form) => {
Object.entries(p.value).forEach(([ form, val ]) => {
if (val === null) return;

_.set(data, [ p.locale, 'plural', form, p.key ], val);
if (!data[p.locale]['plural'][form]) data[p.locale]['plural'][form] = {};

Object.assign(data[p.locale]['plural'][form], { [p.key]: val });
});

});
Expand Down
13 changes: 6 additions & 7 deletions lib/cmd_extract.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
'use strict';


const _ = require('lodash');
const SourceKeys = require('./source_keys');
const TranslationKeys = require('./translation_keys');
const AppError = require('./app_error');
Expand Down Expand Up @@ -103,10 +102,10 @@ File "en-EN.yml", content - "en-GB: ~"
}
});

if (!_.isEmpty(orphaned)) {
if (Object.keys(orphaned).length) {
let msg_orphaned = 'Your translations have orphaned phrases:\n\n';

_.forEach(orphaned, (keys, file) => {
Object.entries(orphaned).forEach(([ file, keys ]) => {
msg_orphaned += ` ${file}\n`;
msg_orphaned += keys.map(k => ` ${k}\n`).join('');
});
Expand All @@ -118,19 +117,19 @@ File "en-EN.yml", content - "en-GB: ~"
//
// fill missed phrases
//
_.forEach(translationKeys.localeDefaultFile, (fileName, locale) => {
_.forEach(sourceKeys.uniques, (keyObj, keyName) => {
Object.entries(translationKeys.localeDefaultFile).forEach(([ locale, fileName ]) => {
Object.entries(sourceKeys.uniques).forEach(([ keyName, keyObj ]) => {
let phraseObj = translationKeys.getPhraseObj(locale, keyName);

if (!phraseObj) {
// Not exists -> add new one
translationKeys.addPhrase({
locale,
key: keyName,
value: !keyObj.plural ? null : _.fromPairs(getPluralKeys(locale).map(k => [ k, null ])),
value: !keyObj.plural ? null : Object.fromEntries(getPluralKeys(locale).map(k => [ k, null ])),
fileName
});
} else if (!_.isPlainObject(phraseObj.value) !== !keyObj.plural) {
} else if (!(phraseObj.value?.constructor === Object) !== !keyObj.plural) {
// Translation already exists -> check type (singular/plural)
// and throw on mismatch
throw new AppError(`
Expand Down
10 changes: 4 additions & 6 deletions lib/compiler_template.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
'use strict';


const _ = require('lodash');

const { create_c_plural_fn } = require('./plurals');


Expand Down Expand Up @@ -51,7 +49,7 @@ function lang_plural_template(l, form, data) {
const loc = to_c(l);
return `
static lv_i18n_phrase_t ${loc}_plurals_${form}[] = {
${_.map(data[l].plural[form], (val, k) => ` {"${esc(k)}", "${esc(val)}"},`).join('\n')}
${Object.entries(data[l].plural[form]).map(([ k, val ]) => ` {"${esc(k)}", "${esc(val)}"},`).join('\n')}
{NULL, NULL} // End mark
};
`.trim();
Expand All @@ -61,7 +59,7 @@ function lang_singular_template(l, data) {
const loc = to_c(l);
return `
static lv_i18n_phrase_t ${loc}_singulars[] = {
${_.map(data[l].singular, (val, k) => ` {"${esc(k)}", "${esc(val)}"},`).join('\n')}
${Object.entries(data[l].singular).map(([ k, val ]) => ` {"${esc(k)}", "${esc(val)}"},`).join('\n')}
{NULL, NULL} // End mark
};
`.trim();
Expand All @@ -73,15 +71,15 @@ function lang_template(l, data) {
const loc = to_c(l);

return `
${!_.isEmpty(data[l].singular) ? lang_singular_template(l, data) : ''}
${Object.keys(data[l].singular).length ? lang_singular_template(l, data) : ''}
${pforms.map(pf => lang_plural_template(l, pf, data)).join('\n\n')}
${create_c_plural_fn(l, `${loc}_plural_fn`)}
static const lv_i18n_lang_t ${loc}_lang = {
.locale_name = "${l}",
${!_.isEmpty(data[l].singular) ? ` .singulars = ${loc}_singulars,` : ''}
${Object.keys(data[l].singular).length ? ` .singulars = ${loc}_singulars,` : ''}
${pforms.map(pf => ` .plurals[${pf_enum[pf]}] = ${loc}_plurals_${pf},`).join('\n')}
.locale_plural_fn = ${loc}_plural_fn
};
Expand Down
14 changes: 8 additions & 6 deletions lib/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,26 @@
'use strict';


const _ = require('lodash');


const defaults = {
singularName: '_',
pluralName: '_p'
};


function escape_re(s) {
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

function create_singular_re(fn_name) {
return new RegExp(
'(?:^|[ =+,;\(])' + _.escapeRegExp(fn_name) + '\\("(.*?)"\\)',
'(?:^|[ =+,;\(])' + escape_re(fn_name) + '\\("(.*?)"\\)',
'g'
);
}

function create_plural_re(fn_name) {
return new RegExp(
'(?:^|[ =+,;\(])' + _.escapeRegExp(fn_name) + '\\("(.*?)",',
'(?:^|[ =+,;\(])' + escape_re(fn_name) + '\\("(.*?)",',
'g'
);
}
Expand Down Expand Up @@ -88,7 +90,7 @@ module.exports = function parse(text, options) {
let singulars = extract(text, s_re).map(o => Object.assign(o, { plural: false }));
let plurals = extract(text, p_re).map(o => Object.assign(o, { plural: true }));

return _.sortBy(singulars.concat(plurals), 'line');
return singulars.concat(plurals).sort((a, b) => a.line - b.line);
};

module.exports._unescape_c = unescape_c;
9 changes: 4 additions & 5 deletions lib/plurals.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
'use strict';


const _ = require('lodash');
const cardinals = require('cldr-core/supplemental/plurals.json').supplemental['plurals-type-cardinal'];


Expand Down Expand Up @@ -83,22 +82,22 @@ module.exports.create_c_plural_fn = function (locale, fn_name) {

let conditions = {};

_.forEach(cldr_rules, (rule, form) => {
Object.entries(cldr_rules).forEach(([ form, rule ]) => {
if (form === 'other') return;

conditions[form] = toSingleRule(rule.split('@')[0].trim());
});

let operands = _.uniq(_.values(conditions).join(' ').match(/[nivwfte]/g) || []);
let operands = [ ...new Set(Object.values(conditions).join(' ').match(/[nivwfte]/g) || []) ]; // unique

let shortcuts = _.uniq(_.values(conditions).join(' ').match(/[nivwfte]\d+/g) || []);
let shortcuts = [ ...new Set(Object.values(conditions).join(' ').match(/[nivwfte]\d+/g) || []) ];
/*eslint-disable max-len*/
return `
static uint8_t ${fn_name}(int32_t num)
{${operands.length ? '\n uint32_t n = op_n(num); UNUSED(n);' : ''}
${operands.map(op => (op !== 'n' ? ` uint32_t ${op} = op_${op}(n); UNUSED(${op});` : '')).filter(Boolean).join('\n')}
${shortcuts.map(sh => ` uint32_t ${sh} = ${sh[0]} % ${sh.slice(1)};`).join('\n')}
${_.map(conditions, (cond, form) => ` if (${cond}) return ${pf_enum[form]};`).join('\n')}
${Object.entries(conditions).map(([ form, cond ]) => ` if (${cond}) return ${pf_enum[form]};`).join('\n')}
return ${pf_enum.other};
}
`.trim();
Expand Down
25 changes: 13 additions & 12 deletions lib/translation_keys.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

const glob = require('glob').sync;
const yaml = require('js-yaml');
const _ = require('lodash');
const debug = require('debug')('translate_keys');
const AppError = require('./app_error');

Expand All @@ -14,7 +13,7 @@ const { readFileSync, writeFileSync } = require('fs');


function isValidSingularValue(val) {
return val === null || _.isString(val);
return val === null || typeof val === 'string';
}

function normalize_locale(l) {
Expand All @@ -38,15 +37,15 @@ module.exports = class TranslationKeys {
// - null (empty)
// - string
// - object (plural)
if (!isValidSingularValue(value) && !_.isPlainObject(value)) {
if (!isValidSingularValue(value) && (value?.constructor !== Object)) {
throw new AppError(`
Error in ${fileName}
Wrong value for '${key}', should be string, plural object or null ('~')
`);
}

// Additional check for plurals
if (_.isPlainObject(value)) {
if (value?.constructor === Object) {
let validKeys = getPluralKeys(locale);
Object.keys(value).forEach(k => {
if (!validKeys.includes(k)) {
Expand Down Expand Up @@ -79,7 +78,7 @@ Bad plural value for '${k}' in '${key}', should be string or null ('~')
}

removePhraseObj(locale, key) {
this.phrases = _.filter(this.phrases, p => !(p.locale === locale && p.key === key));
this.phrases = this.phrases.filter(p => !(p.locale === locale && p.key === key));
}

// convenient for testing, to inline content
Expand All @@ -97,7 +96,7 @@ en-GB: {}
`);
}

if (!_.isPlainObject(obj)) {
if (obj?.constructor !== Object) {
throw new AppError(`
Error in ${fileName}
Can not recognize content. Should be locale with phrase keys (or empty locale):
Expand Down Expand Up @@ -129,7 +128,7 @@ en-GB, ru-RU, en
});

// scan locales data
_.forEach(obj, (content, locale) => {
Object.entries(obj).forEach(([ locale, content ]) => {
debug(`Scan locale ${locale}`);

Object.keys(this.localeDefaultFile).forEach(l => {
Expand All @@ -152,7 +151,7 @@ en-GB, ru-RU, en
// Workaround for special case - empty file with `en-GB:` created manually
if (content === null) content = {};

if (!_.isPlainObject(content)) {
if (content?.constructor !== Object) {
throw new AppError(`
Error in ${fileName}
Locale '${locale}' content should be an object
Expand All @@ -162,7 +161,7 @@ Locale '${locale}' content should be an object
//
// load phrases
//
_.forEach(content, (value, key) => {
Object.entries(content).forEach(([ key, value ]) => {
this.addPhrase({
locale,
key,
Expand All @@ -188,8 +187,10 @@ Locale '${locale}' content should be an object
createFilesData() {
let result = {};

this.phrases.forEach(p => {
_.set(result, [ p.fileName, p.locale, p.key ], p.value);
this.phrases.forEach(({ fileName, locale, key, value }) => {
if (!result[fileName]) result[fileName] = {};
if (!result[fileName][locale]) result[fileName][locale] = {};
result[fileName][locale][key] = value;
});

return result;
Expand All @@ -198,7 +199,7 @@ Locale '${locale}' content should be an object
saveFiles() {
let data = this.createFilesData();

_.forEach(data, (content, fileName) => {
Object.entries(data).forEach(([ fileName, content ]) => {
writeFileSync(fileName, yaml.dump(content, {
styles: {
'!!null': 'canonical'
Expand Down
14 changes: 0 additions & 14 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 0 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
"es6-error": "^4.1.1",
"glob": "^8.0.3",
"js-yaml": "^4.1.0",
"lodash": "^4.17.21",
"shelljs": "^0.8.5"
},
"bundledDependencies": [
Expand All @@ -41,8 +40,6 @@
"es6-error",
"glob",
"js-yaml",
"lodash",
"make-plural",
"shelljs"
],
"devDependencies": {
Expand Down

0 comments on commit b509a1d

Please sign in to comment.