### Install iso-639-1 via NPM
Source: https://github.com/meikidd/iso-639-1/blob/master/readme.md
Use this command to install the package in your project.
```bash
npm install iso-639-1
```
--------------------------------
### getAllNames() Examples
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/iso6391-class.md
Examples of retrieving and interacting with the list of all language names.
```javascript
const names = ISO6391.getAllNames();
// Returns: ['Afar', 'Abkhaz', 'Avestan', ..., 'Zulu']
console.log(names.length); // Approximately 184 languages
console.log(names[0]); // 'Afar'
console.log(names[names.length - 1]); // 'Zulu'
```
--------------------------------
### getCode() Examples
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/iso6391-class.md
Examples of retrieving ISO 639-1 codes using English or native names.
```javascript
ISO6391.getCode('English'); // Returns: 'en'
ISO6391.getCode('English'); // Case-insensitive
ISO6391.getCode('中文'); // Returns: 'zh' (native name works)
ISO6391.getCode('Chinese'); // Returns: 'zh'
ISO6391.getCode('Unknown'); // Returns: ''
```
--------------------------------
### getName() Examples
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/iso6391-class.md
Examples of retrieving English language names by ISO 639-1 code.
```javascript
ISO6391.getName('en'); // Returns: 'English'
ISO6391.getName('zh'); // Returns: 'Chinese'
ISO6391.getName('fr'); // Returns: 'French'
ISO6391.getName('xx'); // Returns: ''
```
--------------------------------
### Install Package via Yarn
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/configuration.md
Standard command to install the package using yarn.
```bash
yarn add iso-639-1
```
--------------------------------
### Comprehensive library usage example
Source: https://github.com/meikidd/iso-639-1/blob/master/readme.md
Demonstrates various methods including name lookup, validation, and batch retrieval.
```javascript
const ISO6391 = require('iso-639-1')
console.log(ISO6391.getName('zh')) // 'Chinese'
console.log(ISO6391.getNativeName('zh')) // '中文'
console.log(ISO6391.getAllNames()) // ['Afar','Abkhaz', ... ,'Zulu']
console.log(ISO6391.getAllNativeNames()) //['Afaraf','аҧсуа бызшәа', ... ,'isiZulu' ]
console.log(ISO6391.getCode('Chinese')) // 'zh'
console.log(ISO6391.getCode('中文')) // 'zh'
console.log(ISO6391.getAllCodes()) //['aa','ab',...,'zu']
console.log(ISO6391.validate('en')) // true
console.log(ISO6391.validate('xx')) // false
console.log(ISO6391.getLanguages(['en', 'zh']))
// [{code:'en',name:'English',nativeName:'English'},{code:'zh',name:'Chinese',nativeName:'中文'}]
```
--------------------------------
### validate() Examples
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/iso6391-class.md
Examples of validating ISO 639-1 codes.
```javascript
ISO6391.validate('en'); // Returns: true
ISO6391.validate('zh'); // Returns: true
ISO6391.validate('xx'); // Returns: false
ISO6391.validate('abc'); // Returns: false
```
--------------------------------
### Configure Rollup for iso-639-1
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/configuration.md
Example configuration for rollup.config.js.
```javascript
// In rollup.config.js
export default {
input: 'src/index.js',
external: [], // iso-639-1 has no dependencies
output: { file: 'dist/bundle.js', format: 'umd' }
};
```
--------------------------------
### getNativeName() Examples
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/iso6391-class.md
Examples of retrieving native language names by ISO 639-1 code.
```javascript
ISO6391.getNativeName('en'); // Returns: 'English'
ISO6391.getNativeName('zh'); // Returns: '中文'
ISO6391.getNativeName('ar'); // Returns: 'العربية'
ISO6391.getNativeName('xx'); // Returns: ''
```
--------------------------------
### Example Language Data Structure
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/types.md
A sample representation of the internal data mapping.
```typescript
{
aa: { name: 'Afar', nativeName: 'Afaraf' },
ab: { name: 'Abkhaz', nativeName: 'аҧсуа бызшәа' },
en: { name: 'English', nativeName: 'English' },
zh: { name: 'Chinese', nativeName: '中文' },
zu: { name: 'Zulu', nativeName: 'isiZulu' }
}
```
--------------------------------
### getAllCodes()
Source: https://github.com/meikidd/iso-639-1/blob/master/readme.md
Get array of all codes.
```APIDOC
## getAllCodes()
### Description
Get array of all codes.
### Returns
- (array) - An array containing all ISO-639-1 codes.
```
--------------------------------
### getAllNames()
Source: https://github.com/meikidd/iso-639-1/blob/master/readme.md
Get array of all language English names.
```APIDOC
## getAllNames()
### Description
Get array of all language English names.
### Returns
- (array) - An array containing all language English names.
```
--------------------------------
### Use LanguageCode for type safety
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/types.md
Examples of using LanguageCode for variable typing, error checking, and function return annotations.
```typescript
// Type-safe code parameter
const code: LanguageCode = 'en';
ISO6391.getName(code); // Type-safe
// Invalid codes cause compilation errors
const badCode: LanguageCode = 'xx'; // Error: Type '"xx"' is not assignable to type 'LanguageCode'
// Return type annotation
function getLanguageInfo(code: LanguageCode): { name: string; native: string } {
return {
name: ISO6391.getName(code),
native: ISO6391.getNativeName(code)
};
}
```
--------------------------------
### getAllNativeNames()
Source: https://github.com/meikidd/iso-639-1/blob/master/readme.md
Get array of all language native names.
```APIDOC
## getAllNativeNames()
### Description
Get array of all language native names.
### Returns
- (array) - An array containing all language native names.
```
--------------------------------
### Importing and Loading the Library
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/OVERVIEW.md
Demonstrates how to import the library in CommonJS, ES Modules, or include it directly in a browser environment.
```javascript
// CommonJS
const ISO6391 = require('iso-639-1');
// ES Modules
import ISO6391 from 'iso-639-1';
// Browser
```
--------------------------------
### Importing the ISO6391 Module
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/iso6391-class.md
Shows how to import the library using either CommonJS or ES Module syntax.
```javascript
// CommonJS
const ISO6391 = require('iso-639-1');
// ES Module
import ISO6391 from 'iso-639-1';
```
--------------------------------
### Building the Browser Bundle
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/configuration.md
Execute the build script to generate a browser-compatible bundle via Webpack.
```bash
npm run build
```
--------------------------------
### Running the Test Suite
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/configuration.md
Execute the test suite using Mocha to verify lookups, validation, and immutability.
```bash
npm test
```
--------------------------------
### Basic usage of iso-639-1 methods
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/README.md
Demonstrates common operations including name retrieval, code validation, and batch lookups.
```javascript
const ISO6391 = require('iso-639-1');
// Get language name by code
ISO6391.getName('en'); // 'English'
ISO6391.getNativeName('zh'); // '中文'
// Get code by name
ISO6391.getCode('French'); // 'fr'
// Validate code
ISO6391.validate('en'); // true
ISO6391.validate('xx'); // false
// Get all languages
ISO6391.getAllCodes(); // ['aa', 'ab', ..., 'zu']
ISO6391.getAllNames(); // ['Afar', 'Abkhaz', ..., 'Zulu']
// Batch lookup
ISO6391.getLanguages(['en', 'fr']);
// [
// { code: 'en', name: 'English', nativeName: 'English' },
// { code: 'fr', name: 'French', nativeName: 'français' }
// ]
```
--------------------------------
### getLanguages(codes)
Source: https://github.com/meikidd/iso-639-1/blob/master/readme.md
Get the array of the language objects by the given codes.
```APIDOC
## getLanguages(codes)
### Description
Get the array of the language objects by the given codes.
### Parameters
- **codes** (array) - Required - An array of ISO-639-1 codes.
### Returns
- (array) - An array of language objects.
```
--------------------------------
### Include via Script Tag
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/OVERVIEW.md
Load the library directly in the browser using a script tag to access the global ISO6391 object.
```html
```
--------------------------------
### Accessing ISO6391 Methods
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/configuration.md
Use static methods directly from the class. Instantiation is unnecessary and discouraged.
```javascript
// Correct
ISO6391.getName('en');
// Incorrect (do not do this)
const instance = new ISO6391();
instance.getName('en'); // Works but unnecessary
```
--------------------------------
### Project File Structure
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/INDEX.md
Displays the directory layout of the project documentation.
```text
/workspace/home/output/
├── README.md # Documentation hub
├── OVERVIEW.md # Architecture & overview
├── CONFIGURATION.md # Setup & installation
├── types.md # TypeScript definitions
├── language-codes-reference.md # All 184 language codes
├── usage-patterns.md # Code examples & patterns
├── INDEX.md # This file
└── api-reference/
├── iso6391-class.md # Complete class reference
└── method-index.md # Quick method lookup
```
--------------------------------
### Include in Browser
Source: https://github.com/meikidd/iso-639-1/blob/master/readme.md
Include the library via a script tag in HTML.
```html
```
--------------------------------
### Package Configuration in package.json
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/configuration.md
Defines the package metadata, entry points, and engine requirements.
```json
{
"name": "iso-639-1",
"version": "3.1.6",
"description": "ISO-639-1 codes",
"main": "./src/index.js",
"type": "commonjs",
"typings": "index.d.ts",
"scripts": {
"build": "webpack",
"test": "mocha"
},
"engines": {
"node": ">=6.0"
}
}
```
--------------------------------
### Unit Testing with Mocha and Chai
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/usage-patterns.md
Demonstrates how to test language lookup and validation functions using the Mocha test runner and Chai assertion library.
```javascript
const chai = require('chai');
const expect = chai.expect;
const ISO6391 = require('iso-639-1');
describe('Language Utilities', function() {
describe('getLanguage', function() {
it('should return valid language info', function() {
const lang = ISO6391.getLanguages(['en'])[0];
expect(lang).to.deep.equal({
code: 'en',
name: 'English',
nativeName: 'English'
});
});
it('should handle invalid codes', function() {
const lang = ISO6391.getLanguages(['xx'])[0];
expect(lang.name).to.equal('');
});
});
describe('validation', function() {
it('should validate correct codes', function() {
expect(ISO6391.validate('en')).to.be.true;
});
it('should reject invalid codes', function() {
expect(ISO6391.validate('xx')).to.be.false;
});
});
});
```
--------------------------------
### Utilize ISO6391 static methods
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/OVERVIEW.md
Demonstrates core lookup, validation, and collection retrieval methods provided by the ISO6391 class.
```javascript
const ISO6391 = require('iso-639-1');
// Lookup methods
ISO6391.getName('en'); // → 'English'
ISO6391.getNativeName('zh'); // → '中文'
ISO6391.getCode('French'); // → 'fr'
ISO6391.validate('en'); // → true
// Collection methods
ISO6391.getAllCodes(); // → ['aa', 'ab', ..., 'zu']
ISO6391.getAllNames(); // → ['Afar', 'Abkhaz', ..., 'Zulu']
ISO6391.getAllNativeNames(); // → ['Afaraf', ..., 'isiZulu']
// Batch method
ISO6391.getLanguages(['en', 'fr']); // → [{code: 'en', name: 'English', ...}, ...]
```
--------------------------------
### Include and use ISO-639-1 in Browser
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/README.md
Direct script inclusion for browser-based projects.
```html
```
--------------------------------
### Import and use as ES Module
Source: https://github.com/meikidd/iso-639-1/blob/master/readme.md
Import the library using ES module syntax.
```javascript
import ISO6391 from 'iso-639-1';
console.log(ISO6391.getName('en')); // 'English'
```
--------------------------------
### Use ISO6391 interface
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/types.md
Shows how to import and use the ISO6391 interface for type-safe method calls.
```typescript
// Import the interface type
import type { ISO6391 } from 'iso-639-1';
// Use for type annotations
const ISO = require('iso-639-1') as ISO6391;
// Type-safe method calls
const name: string = ISO.getName('en');
const codes: LanguageCode[] = ISO.getAllCodes();
```
--------------------------------
### Configure Webpack for iso-639-1
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/configuration.md
Standard import usage for Webpack projects.
```javascript
// No special config needed
import ISO6391 from 'iso-639-1';
```
--------------------------------
### Import and use in Node.js
Source: https://github.com/meikidd/iso-639-1/blob/master/readme.md
Import the library using CommonJS syntax.
```javascript
const ISO6391 = require('iso-639-1');
console.log(ISO6391.getName('en')); // 'English'
```
--------------------------------
### Project Module Structure
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/OVERVIEW.md
Visual representation of the project directory layout and core source files.
```text
iso-639-1/
├── src/
│ ├── index.js # Main entry point (class definition)
│ └── data.js # Language data (184 entries)
├── build/
│ └── index.js # Browser bundle (webpack)
├── index.d.ts # TypeScript declarations
├── package.json # Package metadata
└── test/
└── test.js # Mocha test suite
```
--------------------------------
### Integrate ISO-639-1 with GraphQL
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/usage-patterns.md
Shows schema definition and resolver implementation for querying language information.
```javascript
const { buildSchema, graphql } = require('graphql');
const ISO6391 = require('iso-639-1');
const schema = buildSchema(`
type Language {
code: String!
name: String!
nativeName: String!
}
type Query {
language(code: String!): Language
allLanguages: [Language!]!
}
`);
const resolvers = {
language: ({ code }) => {
const langs = ISO6391.getLanguages([code]);
return langs[0] || null;
},
allLanguages: () => {
return ISO6391.getLanguages(ISO6391.getAllCodes());
}
};
// Usage
graphql(schema, '{ allLanguages { code name } }', resolvers);
```
--------------------------------
### Accessing Browser Global
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/configuration.md
Accessing the library via the window object after script inclusion.
```javascript
// After including build/index.js
console.log(window.ISO6391); // ISO6391 class
ISO6391.validate('en'); // true
```
--------------------------------
### Implement Language Configuration Class
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/usage-patterns.md
Encapsulates language state and validation logic within a class to manage the current application language.
```javascript
class LanguageConfig {
constructor(defaultCode = 'en') {
if (!ISO6391.validate(defaultCode)) {
throw new Error(`Invalid default language: ${defaultCode}`);
}
this.current = defaultCode;
this.supported = ISO6391.getAllCodes();
}
get name() {
return ISO6391.getName(this.current);
}
get nativeName() {
return ISO6391.getNativeName(this.current);
}
setLanguage(code) {
if (!ISO6391.validate(code)) {
console.warn(`Invalid language code: ${code}`);
return false;
}
this.current = code;
return true;
}
getInfo() {
return ISO6391.getLanguages([this.current])[0];
}
}
// Usage
const config = new LanguageConfig('en');
console.log(config.name); // 'English'
config.setLanguage('fr');
console.log(config.name); // 'French'
```
--------------------------------
### Use Language interface
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/types.md
Demonstrates retrieving language objects and handling invalid codes.
```typescript
// From getLanguages()
const languages: Language[] = ISO6391.getLanguages(['en', 'zh']);
// [
// { code: 'en', name: 'English', nativeName: 'English' },
// { code: 'zh', name: 'Chinese', nativeName: '中文' }
// ]
// Type-safe access
languages.forEach(lang => {
console.log(`${lang.code}: ${lang.name}`);
});
// With invalid code
const mixed = ISO6391.getLanguages(['en', 'xx']);
// [
// { code: 'en', name: 'English', nativeName: 'English' },
// { code: 'xx', name: '', nativeName: '' }
// ]
// Check validity
if (mixed[1].name) {
console.log('Valid language');
} else {
console.log('Invalid code:', mixed[1].code);
}
```
--------------------------------
### Lazy Load Language Data in JavaScript
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/usage-patterns.md
Defers the initialization of language data until the first time it is requested to improve startup performance.
```javascript
let languageData = null;
function getLanguageData() {
if (!languageData) {
// Load all languages only when first needed
languageData = ISO6391.getLanguages(ISO6391.getAllCodes());
}
return languageData;
}
// Usage
const data = getLanguageData();
```
--------------------------------
### Implement Language Negotiation
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/usage-patterns.md
Matches user preferences against a list of supported language codes, falling back to a default if no match is found.
```javascript
function negotiateLanguage(userPreferences, supportedCodes) {
// Find first user preference that's supported
for (const code of userPreferences) {
if (ISO6391.validate(code) && supportedCodes.includes(code)) {
return code;
}
}
// Fall back to first supported language
return supportedCodes[0] || 'en';
}
// Usage
const userLangs = ['es', 'fr', 'en'];
const appSupported = ['en', 'de', 'pt'];
const chosen = negotiateLanguage(userLangs, appSupported); // 'en'
```
--------------------------------
### Import and Usage Patterns
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/types.md
Common patterns for importing the library and using its methods in CommonJS and TypeScript.
```javascript
// CommonJS
const ISO6391 = require('iso-639-1');
ISO6391.getName('en'); // 'English'
```
```typescript
// TypeScript with ES modules
import ISO6391 from 'iso-639-1';
ISO6391.getAllCodes(); // Array
```
```typescript
// Type annotation
import ISO6391 from 'iso-639-1';
import type { LanguageCode } from 'iso-639-1';
const code: LanguageCode = 'en';
const name = ISO6391.getName(code);
```
--------------------------------
### Configure Parcel for iso-639-1
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/configuration.md
Parcel requires no specific configuration for this library.
```bash
# No configuration needed
parcel index.js
```
--------------------------------
### Import and use ISO-639-1 in ES Modules
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/README.md
Standard ES module import pattern for modern JavaScript environments.
```javascript
import ISO6391 from 'iso-639-1';
ISO6391.getName('en'); // 'English'
```
--------------------------------
### Runtime Customization Limitations
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/configuration.md
Demonstrates unsupported attempts to modify library behavior at runtime.
```javascript
// Do NOT attempt these (they won't work as intended):
// 1. Trying to configure methods
ISO6391.config = { /* ... */ }; // Ignored
// 2. Trying to add languages at runtime
ISO6391.languages = { xx: { name: 'Example' } }; // Ignored
// 3. Trying to use constructor options
new ISO6391({ /* ... */ }); // Methods still work but options ignored
// 4. Trying to set environment variables
process.env.ISO6391_CUSTOM = 'value'; // No effect
// The library always uses the built-in static data
const allCodes = ISO6391.getAllCodes(); // Always ~184 codes
```
--------------------------------
### Importing with TypeScript
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/configuration.md
Importing the library and the LanguageCode type for type-safe usage.
```typescript
import ISO6391 from 'iso-639-1';
import type { LanguageCode } from 'iso-639-1';
const code: LanguageCode = 'en';
const name = ISO6391.getName(code);
```
--------------------------------
### Implement Safe Error Handling Patterns
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/OVERVIEW.md
Demonstrates how to handle invalid inputs using the library's non-throwing API design. Methods return empty strings or objects when inputs are unrecognized.
```javascript
// Safe error handling patterns
// For lookup methods
const name = ISO6391.getName(userInput);
if (!name) {
console.log('Language code not found');
}
// For getCode
const code = ISO6391.getCode(userInput);
if (!code) {
console.log('Language name not recognized');
}
// For validate
if (!ISO6391.validate(userInput)) {
console.log('Invalid code');
}
// For getLanguages
const results = ISO6391.getLanguages(codes);
results.forEach(result => {
if (!result.name) {
console.log(`Invalid code: ${result.code}`);
}
});
```
--------------------------------
### Import and use ISO-639-1 in CommonJS
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/README.md
Standard CommonJS require pattern for Node.js environments.
```javascript
const ISO6391 = require('iso-639-1');
ISO6391.getName('en'); // 'English'
```
--------------------------------
### getAllCodes()
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/iso6391-class.md
Retrieves an array of all valid ISO 639-1 language codes.
```APIDOC
## static getAllCodes()
### Description
Retrieves an array of all valid ISO 639-1 language codes in alphabetical order.
### Signature
`static getAllCodes(): Array`
### Returns
- **Array** - A new array containing all valid two-letter ISO 639-1 codes.
```
--------------------------------
### Implement a Language Dictionary Class in JavaScript
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/usage-patterns.md
Provides a searchable dictionary class to look up language metadata by code, English name, or native name.
```javascript
class LanguageDictionary {
constructor() {
this.languages = ISO6391.getLanguages(ISO6391.getAllCodes());
this.byCode = new Map();
this.byName = new Map();
this.byNative = new Map();
this.languages.forEach(lang => {
this.byCode.set(lang.code, lang);
this.byName.set(lang.name.toLowerCase(), lang);
this.byNative.set(lang.nativeName.toLowerCase(), lang);
});
}
findByCode(code) {
return this.byCode.get(code) || null;
}
findByName(name) {
return this.byName.get(name.toLowerCase()) || null;
}
findByNative(native) {
return this.byNative.get(native.toLowerCase()) || null;
}
findAny(input) {
return this.findByCode(input) ||
this.findByName(input) ||
this.findByNative(input);
}
}
// Usage
const dict = new LanguageDictionary();
console.log(dict.findByCode('en')); // { code: 'en', name: 'English', ... }
console.log(dict.findByName('French')); // { code: 'fr', name: 'French', ... }
console.log(dict.findByNative('中文')); // { code: 'zh', name: 'Chinese', ... }
console.log(dict.findAny('es')); // { code: 'es', name: 'Spanish', ... }
```
--------------------------------
### Handle invalid inputs in JavaScript
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/method-index.md
Demonstrates that methods return empty strings or false instead of throwing errors for invalid inputs.
```javascript
// All return empty strings, never throw
ISO6391.getName('xx'); // ''
ISO6391.getNativeName('xx'); // ''
ISO6391.getCode('Unknown'); // ''
// Invalid codes in batch return empty-name objects
ISO6391.getLanguages(['en', 'xx']).forEach(lang => {
if (lang.name === '') {
console.log(`Invalid code: ${lang.code}`);
}
});
// validate() returns false, never throws
if (!ISO6391.validate(userInput)) {
console.log('Invalid');
}
```
--------------------------------
### Integrate ISO-639-1 with Express.js
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/usage-patterns.md
Demonstrates language validation middleware and endpoint implementation for retrieving language data.
```javascript
const express = require('express');
const ISO6391 = require('iso-639-1');
const app = express();
// Language validation middleware
app.use((req, res, next) => {
const lang = req.query.lang || 'en';
if (!ISO6391.validate(lang)) {
res.status(400).json({ error: 'Invalid language code' });
return;
}
req.language = lang;
next();
});
// Endpoint: Get language info
app.get('/language/:code', (req, res) => {
if (!ISO6391.validate(req.params.code)) {
res.status(404).json({ error: 'Language not found' });
return;
}
res.json(ISO6391.getLanguages([req.params.code])[0]);
});
// Endpoint: List all languages
app.get('/languages', (req, res) => {
res.json(ISO6391.getLanguages(ISO6391.getAllCodes()));
});
```
--------------------------------
### Retrieve all ISO 639-1 language codes
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/iso6391-class.md
Returns an array of all valid two-letter ISO 639-1 codes in alphabetical order.
```javascript
static getAllCodes(): Array
```
```javascript
const codes = ISO6391.getAllCodes();
// Returns: ['aa', 'ab', 'ae', 'af', ..., 'zu']
console.log(codes.length); // Approximately 184 codes
console.log(codes[0]); // 'aa'
console.log(codes[codes.length - 1]); // 'zu'
// Verify all codes are valid
codes.forEach(code => {
if (!ISO6391.validate(code)) {
console.error('Invalid code in list:', code);
}
});
```
--------------------------------
### Build a language selector
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/iso6391-class.md
Transform all language data into a format suitable for dropdown or select UI components.
```javascript
// Create a dropdown/select with all languages
const allLanguages = ISO6391.getLanguages(ISO6391.getAllCodes());
const options = allLanguages.map(lang => ({
value: lang.code,
label: `${lang.name} (${lang.nativeName})`
}));
```
--------------------------------
### ISO6391.getAllCodes()
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/language-codes-reference.md
Retrieves an array of all available ISO 639-1 language codes.
```APIDOC
### Method
`ISO6391.getAllCodes()`
### Description
Returns an array containing all ISO 639-1 language codes as strings.
### Returns
- **Array** - A list of all language codes.
```
--------------------------------
### Create Language Selection Dropdown
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/README.md
Maps all language codes to an array of objects suitable for dropdown components.
```javascript
const allLanguages = ISO6391.getLanguages(ISO6391.getAllCodes());
const options = allLanguages.map(lang => ({
value: lang.code,
label: `${lang.name} (${lang.nativeName})`
}));
```
--------------------------------
### Dropdown Builder Pattern
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/method-index.md
Generates a list of objects suitable for populating UI dropdown components.
```javascript
function buildLanguageOptions() {
return ISO6391.getLanguages(ISO6391.getAllCodes())
.map(lang => ({
value: lang.code,
label: `${lang.name} (${lang.nativeName})`
}));
}
```
--------------------------------
### Retrieve all language codes
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/language-codes-reference.md
Returns an array of all available ISO 639-1 language codes.
```javascript
const allCodes = ISO6391.getAllCodes();
// ['aa', 'ab', 'ae', ..., 'zu']
```
--------------------------------
### ISO6391 Methods
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/README.md
A collection of methods for retrieving language names, codes, and validation status.
```APIDOC
## getName(code)
### Description
Retrieves the English language name associated with the provided ISO 639-1 code.
### Parameters
- **code** (string) - Required - The ISO 639-1 language code.
## getNativeName(code)
### Description
Retrieves the native language name associated with the provided ISO 639-1 code.
### Parameters
- **code** (string) - Required - The ISO 639-1 language code.
## getCode(name)
### Description
Retrieves the ISO 639-1 code associated with the provided English or native language name.
### Parameters
- **name** (string) - Required - The language name.
## validate(code)
### Description
Checks if the provided string is a valid ISO 639-1 language code.
### Parameters
- **code** (string) - Required - The code to validate.
## getAllCodes()
### Description
Returns an array containing all valid ISO 639-1 language codes.
## getAllNames()
### Description
Returns an array containing all English language names.
## getAllNativeNames()
### Description
Returns an array containing all native language names.
## getLanguages(codes)
### Description
Retrieves an array of language objects for the provided list of codes.
### Parameters
- **codes** (string[]) - Required - An array of ISO 639-1 language codes.
```
--------------------------------
### Create Language Dropdown in Vanilla JavaScript
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/usage-patterns.md
Dynamically generates a select element populated with language names and native names.
```javascript
// Build dropdown options
function createLanguageDropdown() {
const select = document.createElement('select');
const languages = ISO6391.getLanguages(ISO6391.getAllCodes());
languages.forEach(lang => {
const option = document.createElement('option');
option.value = lang.code;
option.text = `${lang.name} (${lang.nativeName})`;
select.appendChild(option);
});
return select;
}
// Usage
const dropdown = createLanguageDropdown();
document.body.appendChild(dropdown);
```
--------------------------------
### Access global variable in Browser
Source: https://github.com/meikidd/iso-639-1/blob/master/readme.md
Access the library via the global ISO6391 variable after script inclusion.
```javascript
console.log(ISO6391.getName('en')); // 'English'
```
--------------------------------
### Create lookup tables for language data
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/usage-patterns.md
Generates mapping objects for quick access between codes and names.
```javascript
// Code to name mapping
const codeToName = {};
ISO6391.getAllCodes().forEach((code, i) => {
codeToName[code] = ISO6391.getAllNames()[i];
});
console.log(codeToName['es']); // 'Spanish'
// Name to code mapping
const nameToCode = {};
ISO6391.getAllNames().forEach(name => {
const code = ISO6391.getCode(name);
nameToCode[name] = code;
});
console.log(nameToCode['Chinese']); // 'zh'
```
--------------------------------
### Import and use ISO-639-1 in TypeScript
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/README.md
Type-safe usage including the LanguageCode interface.
```typescript
import ISO6391 from 'iso-639-1';
import type { LanguageCode } from 'iso-639-1';
const code: LanguageCode = 'en';
ISO6391.getName(code);
```
--------------------------------
### Enumerate all languages
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/iso6391-class.md
Retrieve all available language codes and names, or map them into language objects.
```javascript
// Get all language codes and their names
const allCodes = ISO6391.getAllCodes();
const allNames = ISO6391.getAllNames();
allCodes.forEach((code, index) => {
console.log(`${code}: ${allNames[index]}`);
});
// Or get all languages as objects
const allLanguages = ISO6391.getLanguages(ISO6391.getAllCodes());
allLanguages.forEach(lang => {
console.log(`${lang.code}: ${lang.name}`);
});
```
--------------------------------
### Retrieve all language names
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/method-index.md
Returns an array of all available language names in alphabetical order.
```javascript
ISO6391.getAllNames();
// ['Afar', 'Abkhaz', 'Avestan', 'Afrikaans', ..., 'Zulu']
// ~184 names in alphabetical order
```
--------------------------------
### getCode(name: string)
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/types.md
Retrieves a language code by name, returning a union type.
```APIDOC
## getCode(name: string)
### Description
Returns the LanguageCode associated with the provided language name. If the name is not found, it returns an empty string.
### Signature
`getCode: (name: string) => LanguageCode | ""`
### Usage
```typescript
const code = ISO6391.getCode('English');
if (code) {
// code is LanguageCode
} else {
// code is ""
}
```
```
--------------------------------
### Use getCode return type
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/types.md
Handling the union return type of getCode by checking for the empty string fallback.
```typescript
const code = ISO6391.getCode('English');
if (code) {
// code is LanguageCode here (empty string is falsy)
useCode(code);
} else {
// code is "" (empty string)
handleMissingLanguage();
}
// Or use type guard
if (code && ISO6391.validate(code)) {
// Explicit type guard for clarity
processLanguage(code);
}
```
--------------------------------
### ISO6391 Interface Methods
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/iso6391-class.md
The library exposes an interface for querying language information based on ISO 639-1 codes or English names.
```APIDOC
## ISO6391 Methods
### getName(code: string) -> string
Returns the English name of the language for the given ISO 639-1 code.
### getAllNames() -> Array
Returns an array of all available English language names.
### getNativeName(code: string) -> string
Returns the native name of the language for the given ISO 639-1 code.
### getAllNativeNames() -> Array
Returns an array of all available native language names.
### getCode(name: string) -> LanguageCode | ""
Returns the ISO 639-1 code for a given English language name, or an empty string if not found.
### getAllCodes() -> Array
Returns an array of all valid ISO 639-1 language codes.
### validate(code: string) -> boolean
Validates whether the provided string is a valid ISO 639-1 language code.
### getLanguages(codes: Array) -> Array<{code: LanguageCode, name: string, nativeName: string}>
Returns an array of language objects containing code, name, and nativeName for the provided list of codes.
```
--------------------------------
### getCode(name)
Source: https://github.com/meikidd/iso-639-1/blob/master/readme.md
Lookup code by English name or native name.
```APIDOC
## getCode(name)
### Description
Lookup code by English name or native name.
### Parameters
- **name** (string) - Required - The English or native name of the language.
### Returns
- (string) - The ISO-639-1 language code.
```
--------------------------------
### Search through languages
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/method-index.md
Use getAllNames or getAllNativeNames to retrieve a list of all available names for filtering or search functionality.
```javascript
const query = 'fren'; // User typed 'fren...'
const names = ISO6391.getAllNames();
const matching = names.filter(name =>
name.toLowerCase().includes(query.toLowerCase())
); // ['French']
```
--------------------------------
### Format Language Display Strings in JavaScript
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/usage-patterns.md
Constructs a standardized object containing English, native, and combined display names for a given ISO-639-1 code.
```javascript
function getLanguageDisplay(code) {
if (!ISO6391.validate(code)) {
return null;
}
return {
code: code,
english: ISO6391.getName(code),
native: ISO6391.getNativeName(code),
display: `${ISO6391.getName(code)} (${ISO6391.getNativeName(code)})`
};
}
// Usage
const display = getLanguageDisplay('ja');
// {
// code: 'ja',
// english: 'Japanese',
// native: '日本語',
// display: 'Japanese (日本語)'
// }
console.log(display.display); // Japanese (日本語)
```
--------------------------------
### getAllNames() Method Definition
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/iso6391-class.md
Signature for retrieving all English language names.
```typescript
static getAllNames(): Array
```
--------------------------------
### Import via Browser Bundler
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/OVERVIEW.md
Use standard ES module imports when working with bundlers like Webpack, Rollup, or Vite.
```javascript
// webpack, Rollup, Parcel, Vite, etc. (no special config needed)
import ISO6391 from 'iso-639-1';
ISO6391.validate('en'); // true
```
--------------------------------
### Cache Language Lookups in JavaScript
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/usage-patterns.md
Implements a simple class-based cache to avoid redundant library calls for language name lookups.
```javascript
class LanguageCache {
constructor() {
this.cache = {};
}
getName(code) {
if (!(code in this.cache)) {
this.cache[code] = ISO6391.getName(code);
}
return this.cache[code];
}
clear() {
this.cache = {};
}
}
// Usage
const cache = new LanguageCache();
const name1 = cache.getName('en'); // Lookup
const name2 = cache.getName('en'); // From cache
```
--------------------------------
### Find language code from input
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/method-index.md
Use getCode to resolve a language name or native name string into its corresponding ISO-639-1 code.
```javascript
const code = ISO6391.getCode('Spanish'); // 'es'
const code2 = ISO6391.getCode('Español'); // 'es'
```
--------------------------------
### Define ISO-639-1 TypeScript signatures
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/method-index.md
Provides the static class definition and method signatures for TypeScript integration.
```typescript
class ISO6391 {
static getName(code: string): string;
static getNativeName(code: string): string;
static getCode(name: string): string;
static validate(code: string): boolean;
static getAllNames(): Array;
static getAllNativeNames(): Array;
static getAllCodes(): Array;
static getLanguages(codes?: Array): Array<{
code: string;
name: string;
nativeName: string;
}>;
}
```
--------------------------------
### Perform batch operations
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/iso6391-class.md
Retrieve information for multiple language codes simultaneously using an array.
```javascript
// Get info for multiple languages at once
const selectedLanguages = ['en', 'zh', 'ar', 'ja'];
const languages = ISO6391.getLanguages(selectedLanguages);
languages.forEach(lang => {
if (lang.name) {
console.log(`${lang.code}: ${lang.name} (${lang.nativeName})`);
}
});
```
--------------------------------
### Perform batch lookups
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/method-index.md
Pass an array of codes to getLanguages to retrieve full language details for multiple entries at once.
```javascript
const selected = ['en', 'fr', 'zh'];
const languages = ISO6391.getLanguages(selected);
// [
// { code: 'en', name: 'English', nativeName: 'English' },
// { code: 'fr', name: 'French', nativeName: 'français' },
// { code: 'zh', name: 'Chinese', nativeName: '中文' }
// ]
```
--------------------------------
### Build Locale Objects
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/usage-patterns.md
Encapsulates language data retrieval into a class to generate standardized locale objects.
```javascript
class LocaleBuilder {
constructor() {
this.languages = ISO6391.getLanguages(ISO6391.getAllCodes());
}
buildLocale(code) {
const lang = this.languages.find(l => l.code === code);
if (!lang) return null;
return {
code: lang.code,
language: lang.name,
nativeName: lang.nativeName,
bcp47: lang.code, // BCP 47 would need iso-639-3 for full support
displayName: `${lang.name} (${lang.nativeName})`
};
}
}
// Usage
const builder = new LocaleBuilder();
const locale = builder.buildLocale('pt');
// { code: 'pt', language: 'Portuguese', nativeName: 'português', ... }
```
--------------------------------
### Define ISO6391 interface
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/types.md
Defines the static methods available in the ISO6391 namespace.
```typescript
interface ISO6391 {
getName: (code: string) => string;
getAllNames: () => Array;
getNativeName: (code: string) => string;
getAllNativeNames: () => Array;
getCode: (name: string) => LanguageCode | "";
getAllCodes: () => Array;
validate: (code: string) => code is LanguageCode;
getLanguages: (codes: Array) => Array;
}
```
--------------------------------
### Retrieve all language names for display in JavaScript
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/usage-patterns.md
Fetch arrays of all available English or native language names.
```javascript
// Get all language names (English)
const allNames = ISO6391.getAllNames();
console.log(allNames);
// ['Afar', 'Abkhaz', 'Avestan', ..., 'Zulu']
// Get all native language names
const nativeNames = ISO6391.getAllNativeNames();
console.log(nativeNames);
// ['Afaraf', 'аҧсуа бызшәа', 'avesta', ..., 'isiZulu']
```
--------------------------------
### ISO6391.getCode(name)
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/language-codes-reference.md
Retrieves the ISO 639-1 code for a given language name.
```APIDOC
## ISO6391.getCode(name)
### Description
Returns the ISO 639-1 code corresponding to the provided language name (English or native).
### Parameters
- **name** (string) - Required - The name of the language.
```
--------------------------------
### Verify immutability of returned arrays
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/method-index.md
Shows that collection methods return defensive copies, ensuring internal state remains unaffected by external mutations.
```javascript
const codes1 = ISO6391.getAllCodes();
const codes2 = ISO6391.getAllCodes();
console.log(codes1 === codes2); // false (different arrays)
codes1.push('xx'); // Does not affect internal state
const codes3 = ISO6391.getAllCodes();
console.log(codes3.length === codes1.length); // false
// Original state unchanged
```
--------------------------------
### Usage of Static Methods
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/iso6391-class.md
The class is designed for static access only and should not be instantiated.
```javascript
// Do NOT instantiate
// const instance = new ISO6391(); // Wrong
// Use static methods directly
ISO6391.getName('en'); // Correct
```
--------------------------------
### Retrieve language names
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/method-index.md
Use getName or getNativeName to display language labels to users based on a language code.
```javascript
const name = ISO6391.getName('en'); // 'English'
const native = ISO6391.getNativeName('en'); // 'English'
```
--------------------------------
### Manage User Language Preferences
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/usage-patterns.md
Persists and retrieves a validated language code using localStorage, defaulting to 'en' if invalid or missing.
```javascript
// Save to localStorage
function setUserLanguage(code) {
if (!ISO6391.validate(code)) {
throw new Error('Invalid language code');
}
localStorage.setItem('userLanguage', code);
}
// Load from localStorage
function getUserLanguage() {
const stored = localStorage.getItem('userLanguage');
if (stored && ISO6391.validate(stored)) {
return stored;
}
// Default to browser language or 'en'
return 'en';
}
// Usage
setUserLanguage('es');
const lang = getUserLanguage(); // 'es'
const name = ISO6391.getName(lang); // 'Spanish'
```
--------------------------------
### Retrieve language name by code
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/method-index.md
Returns the English name for a given ISO 639-1 code. Returns an empty string if the code is invalid.
```javascript
ISO6391.getName('en'); // 'English'
ISO6391.getName('zh'); // 'Chinese'
ISO6391.getName('ar'); // 'Arabic'
ISO6391.getName('xx'); // ''
```
--------------------------------
### ISO6391.getCode(name)
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/iso6391-class.md
Retrieves the ISO 639-1 code of a language by its English or native name.
```APIDOC
## ISO6391.getCode(name)
### Description
Retrieves the ISO 639-1 code of a language by its English or native name. Lookup is case-insensitive.
### Parameters
- **name** (string) - Required - Language name in English or native form.
### Return Type
- **string** - The ISO 639-1 code (two lowercase letters). Returns an empty string '' if the name is not found.
```
--------------------------------
### Filter languages by name using ISO-639-1
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/api-reference/method-index.md
Retrieves all language codes and filters the resulting language objects by name prefix.
```javascript
// Example: Get all languages, filter by name, get details
const allCodes = ISO6391.getAllCodes();
const allLanguages = ISO6391.getLanguages(allCodes);
// Find all languages starting with 'C'
const startsWithC = allLanguages.filter(lang =>
lang.name.startsWith('C')
);
// [
// { code: 'ca', name: 'Catalan', nativeName: 'català' },
// { code: 'ch', name: 'Chamorro', nativeName: 'Chamoru' },
// ...
// ]
```
--------------------------------
### Implement Language Selector in Vue
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/usage-patterns.md
A single-file component using v-model for binding and v-for for rendering the language list.
```vue
```
--------------------------------
### getName(code)
Source: https://github.com/meikidd/iso-639-1/blob/master/readme.md
Lookup language English name by code.
```APIDOC
## getName(code)
### Description
Lookup language English name by code.
### Parameters
- **code** (string) - Required - The ISO-639-1 language code.
### Returns
- (string) - The English name of the language.
```
--------------------------------
### Look Up Language Code by Name
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/README.md
Retrieves the ISO 639-1 code using either the English or native language name.
```javascript
const code = ISO6391.getCode('Spanish'); // 'es'
const code2 = ISO6391.getCode('Español'); // 'es' (works with native names)
```
--------------------------------
### Use validate type guard
Source: https://github.com/meikidd/iso-639-1/blob/master/_autodocs/types.md
Demonstrates narrowing a string to LanguageCode using the validate method.
```typescript
function processLanguageCode(code: string) {
if (ISO6391.validate(code)) {
// Type narrowed to LanguageCode here
const name: string = ISO6391.getName(code);
const codes: LanguageCode[] = [code]; // Valid assignment
} else {
// Type remains string here
console.error(`Invalid code: ${code}`);
}
}
// Type-safe conditional
const maybeCode: string = getUserInput();
if (ISO6391.validate(maybeCode)) {
// maybeCode is now typed as LanguageCode
displayLanguage(maybeCode); // Type-safe function call
}
```