Generate Unique IDs Like Youtube In JavaScript – Hashids

Category: Javascript , Recommended | November 10, 2019
Author: niieani
Views Total: 166
Official Page: Go to website
Last Update: November 10, 2019
License: MIT

Preview:

Generate Unique IDs Like Youtube In JavaScript – Hashids

Description:

Hashids is an ID generator & number encoder that converts numeric values (or hex values) into Youtube video ID like unique IDs.

How to use it:

Install the Hashids package.

# NPM
$ npm install hashids --save

Import the Hashids module.

import Hashids from './lib/hashids.js'

Initialize the Hashids.

var myHashId = new Hashids();

Encode a number or hex.

// Mj3
hashids.encode(123);

// LPj9LA
hashids.encodeHex('fafafa');

Decode the generated IDs.

hashids.decode(id);
hashids.decodeHex(id);

Config the library by passing the following parameters:

  • salt: defaults to ”
  • minLength: defaults to 0
  • alphabet: defaults to ‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890’
// Hashids(salt, minLength, alphabet)
var myHashId = new Hashids(0, 5, 'abc');

Check if is valid.

hashids.isValidId(id);

Changelog:

v2.1.0 (11/10/2019)

  • protect from an infinite loop by validating IDs
  • add a public method hashids.isValidId(id) that validates the ID

You Might Be Interested In:


Leave a Reply