diff --git a/src/cli/extract.ts b/src/cli/extract.ts index 48ebd89..603e118 100755 --- a/src/cli/extract.ts +++ b/src/cli/extract.ts @@ -16,6 +16,7 @@ const options = cli.parse({ output: ['o', 'Path you would like to save extracted strings to', 'dir', process.env.PWD], format: ['f', 'Output format', ['json', 'pot'], 'json'], replace: ['r', 'Replace the contents of output file if it exists (Merges by default)', 'boolean', false], + sort: ['s', 'Sort translations in the output file in alphabetical order', 'boolean', false], clean: ['c', 'Remove obsolete strings when merging', 'boolean', false] }); @@ -77,6 +78,10 @@ try { } } + if (options.sort) { + collection = collection.sort(); + } + fs.writeFileSync(outputPath, compiler.compile(collection)); cli.ok(`* Saved to '${outputPath}'`); } catch (e) { diff --git a/src/utils/translation.collection.ts b/src/utils/translation.collection.ts index ced5f94..9239ba6 100644 --- a/src/utils/translation.collection.ts +++ b/src/utils/translation.collection.ts @@ -75,4 +75,17 @@ export class TranslationCollection { return Object.keys(this.values).length === 0; } + public sort(compareFn?: (a: string, b: string) => number): TranslationCollection { + if (!compareFn) { + // if no compare functions is provided use a case insensitive sorting function + compareFn = (a, b) => a.toLowerCase().localeCompare(b.toLowerCase()); + } + + let collection = new TranslationCollection(); + let sortedKeys = this.keys().sort(compareFn); + sortedKeys.forEach((key) => { + collection = collection.add(key, this.get(key)); + }); + return collection; + } } diff --git a/tests/utils/translation.collection.spec.ts b/tests/utils/translation.collection.spec.ts index c9e51b2..1d98312 100644 --- a/tests/utils/translation.collection.spec.ts +++ b/tests/utils/translation.collection.spec.ts @@ -79,4 +79,10 @@ describe('StringCollection', () => { expect(collection.intersect(newCollection).values).to.deep.equal({ red: 'rød', blue: 'blå' }); }); + it('should sort translations in alphabetical order', () => { + collection = new TranslationCollection({ red: 'rød', green: 'grøn', blue: 'blå' }); + collection = collection.sort(); + expect(collection.keys()).deep.equal(['blue', 'green', 'red']); + }); + });