als-lang

1.3.0 • Public • Published

als-Lang Library Documentation

Lang is a lightweight library for handling automatic text translations with customizable markers. It works both in Node.js and browser environments.

Change Log for 1.2.0

  • Error Handling Update:
    Previous behavior of throwing an error when the number of translations did not match the number of languages has been replaced. Now, missing translations are filled with empty strings ('').

  • New Methods Added:

    1. add(items): Adds new key-value pairs to the existing dictionary. For each key, translations are added for the existing languages, with missing translations filled as empty strings.
    2. merge(data): Creates a new Lang instance by merging the current instance with the provided data. Combines dictionaries, with priority given to the current instance's data when conflicts arise.

Installation

npm install lang-library

Initialization

Import the Library

In Node.js:

const Lang = require('lang-library');

In the browser:

<script src="/node_modules/als-lang/lang.js"></script>
<!-- or Minified: -->
<script src="/node_modules/als-lang/lang.min.js"></script>

Create an Instance

const data = {
  dictionary: {
    'Hello, world!': ['Привет, мир!', 'Hola, mundo!'],
    'How are you?': ['Как дела?', '¿Cómo estás?'],
  },
  langs: ['ru', 'es'],
};

const translator = new Lang(data, 'ru'); // Default language is Russian
  • dictionary: An object where keys are original phrases, and values are arrays of translations for each language.
  • langs: An array of language codes (e.g., ['ru', 'es']).
  • defaultLang: (Optional) The fallback language code when a translation is unavailable. Defaults to 'en'.

Methods

dictionaryFn(lang)

Returns a function that takes text and translates it into the specified language if a translation exists. If no translation is available, it returns the original text.

Parameters:

  • lang: The target language code.

Example:

const translator = new Lang(data, 'ru');
const translate = translator.dictionaryFn('ru');

console.log(translate('Hello, world!')); 
// Output: Привет, мир!

console.log(translate('Unknown phrase'));
// Output: Unknown phrase

replace(text, lang)

Replaces all occurrences of text wrapped in the defined markers (~...~) with the corresponding translation. Internally uses the dictionaryFn method to fetch translations.

Parameters:

  • text: The string containing text wrapped in markers (e.g., ~Hello, world!~).
  • lang: The target language code for the translation.

Example:

const text = 'Welcome! ~Hello, world!~ ~How are you?~';
console.log(translator.replace(text, 'ru'));
// Output: Welcome! Привет, мир! Как дела?

console.log(translator.replace(text, 'es'));
// Output: Welcome! Hola, mundo! ¿Cómo estás?

If the translation for the specified language is not available, the original text is returned:

console.log(translator.replace(text, 'fr'));
// Output: Welcome! Hello, world! How are you?

Custom Markers

By default, ~ is used as the start and end marker. You can change it globally:

Lang._start = '{{';
Lang._end = '}}';

const customTranslator = new Lang(data, 'ru');
const text = 'Welcome! {{Hello, world!}} {{How are you?}}';
console.log(customTranslator.replace(text, 'ru'));
// Output: Welcome! Привет, мир! Как дела?

Note: Markers must be the same for all instances.

Error Handling

  1. Invalid Language Array:
    • If langs is not an array, an error will be thrown:
    const invalidData = { dictionary: {}, langs: 'ru, es' };
    new Lang(invalidData); // Error: Langs must be an array

Examples

Basic Translation

const data = {
  dictionary: {
    'Welcome!': ['Добро пожаловать!', '¡Bienvenidos!'],
  },
  langs: ['ru', 'es'],
};

const translator = new Lang(data, 'ru');
console.log(translator.replace('~Welcome!~', 'ru'));
// Output: Добро пожаловать!

Fallback Language

const translator = new Lang(data, 'es'); // Default is Spanish
console.log(translator.replace('~Welcome!~', 'fr')); 
// Output: ¡Bienvenidos!

Empty Dictionary

const emptyData = { dictionary: {}, langs: ['ru', 'es'] };
const translator = new Lang(emptyData);

console.log(translator.replace('~Unknown phrase~', 'ru'));
// Output: Unknown phrase

Method add(items)

Description

The add method allows you to dynamically add new translations to the existing Lang instance. If a translation for a specific language is missing, it is automatically filled with an empty string ('').

Parameters:

  • items: An object where keys are original phrases, and values are arrays of translations for each language.

Example Usage:

const lang = new Lang({
  langs: ['en', 'es'],
  dictionary: { hello: ['Hello', 'Hola'] },
});

lang.add({
  goodbye: ['Goodbye', 'Adiós'],
  world: ['World'], // Spanish translation missing
});

console.log(lang.langs);
// Output:
// {
//   en: { hello: 'Hello', goodbye: 'Goodbye', world: 'World' },
//   es: { hello: 'Hola', goodbye: 'Adiós', world: '' },
// }

Method merge(data)

Description

The merge method creates a new Lang instance by combining the current instance's data with the provided data. The method ensures that translations from the current instance take precedence in case of conflicts.

Parameters:

  • data: An object with langs (array) and dictionary (object) properties to merge into the current instance or another Lang instance.

Example Usage:

const lang1 = new Lang({
  langs: ['en', 'es'],
  dictionary: { hello: ['Hello', 'Hola'] },
});

const mergedLang = lang1.merge({
  langs: ['en', 'fr'], // Adding French
  dictionary: { goodbye: ['Goodbye', 'Au revoir'], hello: ['Hi', 'Salut'] },
});

// Or

const mergedLang = lang1.merge(new Lang({
  langs: ['en', 'fr'], // Adding French
  dictionary: { goodbye: ['Goodbye', 'Au revoir'], hello: ['Hi', 'Salut'] },
}));


console.log(mergedLang.langs);
// Output:
// {
//   en: { hello: 'Hello', goodbye: 'Goodbye' },
//   es: { hello: 'Hola', goodbye: '' },
//   fr: { hello: 'Salut', goodbye: 'Au revoir' },
// }

Notes

  • The library works seamlessly in both Node.js and browser environments.
  • Translations should be provided as arrays with values matching the order of langs.
  • Custom markers (start and end) must be globally consistent for all instances.
    • The add method allows dynamic updates to the dictionary, filling missing translations with empty strings ('').
  • The merge method creates a new Lang instance by combining data from two sources, with the current instance's data taking precedence.

Readme

Keywords

none

Package Sidebar

Install

npm i als-lang

Weekly Downloads

2

Version

1.3.0

License

MIT

Unpacked Size

21.4 kB

Total Files

7

Last publish

Collaborators

  • alexsorkin