UNPKG

@vendure/ngx-translate-extract

Version:
101 lines (100 loc) 3.22 kB
import { normalizeFilePath } from './fs-helpers.js'; export class TranslationCollection { values = {}; constructor(values = {}) { this.values = values; } add(key, val, sourceFile) { const translation = this.values[key] ? { ...this.values[key] } : { value: val, sourceFiles: [] }; translation.sourceFiles.push(normalizeFilePath(sourceFile)); return new TranslationCollection({ ...this.values, [key]: translation }); } addKeys(keys, sourceFile) { const values = keys.reduce((results, key) => ({ ...results, [key]: { value: '', sourceFiles: [normalizeFilePath(sourceFile)] } }), {}); return new TranslationCollection({ ...this.values, ...values }); } remove(key) { return this.filter((k) => key !== k); } forEach(callback) { Object.keys(this.values).forEach((key) => callback.call(this, key, this.values[key])); return this; } filter(callback) { const values = {}; this.forEach((key, val) => { if (callback.call(this, key, val)) { values[key] = val; } }); return new TranslationCollection(values); } map(callback) { const values = {}; this.forEach((key, val) => { values[key] = callback.call(this, key, val); }); return new TranslationCollection(values); } union(collection) { return new TranslationCollection({ ...this.values, ...collection.values }); } intersect(collection) { const values = {}; this.filter((key) => collection.has(key)).forEach((key, val) => { values[key] = val; }); return new TranslationCollection(values); } has(key) { return Object.hasOwn(this.values, key); } get(key) { return this.values[key]; } keys() { return Object.keys(this.values); } count() { return Object.keys(this.values).length; } isEmpty() { return Object.keys(this.values).length === 0; } sort(compareFn) { const values = {}; this.keys() .sort(compareFn) .forEach((key) => { values[key] = this.get(key); }); return new TranslationCollection(values); } toKeyValueObject() { const jsonTranslations = {}; Object.entries(this.values).map(([key, value]) => jsonTranslations[key] = value.value); return jsonTranslations; } stripKeyPrefix(prefix) { const cleanedValues = {}; const lowercasePrefix = prefix.toLowerCase(); for (const key in this.values) { if (this.has(key)) { const lowercaseKey = key.toLowerCase(); if (lowercaseKey.startsWith(lowercasePrefix)) { const cleanedKey = key.substring(prefix.length); cleanedValues[cleanedKey] = this.values[key]; } else { cleanedValues[key] = this.values[key]; } } } return new TranslationCollection(cleanedValues); } }