Generate random, unique string in JavaScript

Whether you need to generate a unique identifier for data key, object reference, url shortener, or duplication avoidance, a good random value generator library is a must-have. I recommend 4 libraries: uuid, short-uuid, nanoid, and crypto-random-string

This is not something you want to implement ad-hoc naively because there are serious number theory considerations were already put into these libraries to minimize collision probability thus enhance safety and more suitable for cryptography related use cases.

uuid is a straightforward way to generate standard RFC4122 UUIDs (128-bit Universally Unique Identifier)

const { v4: uuidv4 } = require('uuid')
uuidv4() // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'

short-uuid serves similar purpose like above but allows converting back and forth between UUID and a shorter format for storage efficiency.

const short = require('short-uuid')

// Generate a shortened v4 UUID
const shortId = translator.new() //=>  mhvXdrZT4jP5T8vBxuvm75
 
// Translate UUIDs to and from the shortened format
const regularUUID = translator.toUUID(shortId); 
// a44521d0-0fb8-4ade-8002-3385545c3318
translator.fromUUID(regularUUID) // => mhvXdrZT4jP5T8vBxuvm75

nanoid is another alternative to UUID that has similar mathematical properties but designed to be faster and more compact by using a larger alphabet than UUID therefore less characters needed, whereby the size and alphabet are customizable. Moreover, there is also an async API that allows collecting more entropy by acquiring CPU noise in the background.

const nanoid = require('nanoid').nanoid

nanoid() //=> V1StGXR8_Z5jdHi6B-myT
// custom size, trade off between less storage and more collision probability
nanoid(10) //=> IRFa-VaY2b

crypto-random-string is a utility that generates random string with flexible customization. It worries less about collision probability, so it’s best suit where UUID is not needed and you care more about output representation.

(more…)

Escape JavaScript Regex characters using Lodash

Sometimes you want to construct a Regular Expression object dynamically from a string instead of a literal regex. It’s important to safely escape special characters in the string that is not intended to be regex syntax. Turned out, the swift army knife Lodash library has a dedicated escapeRegExp method for this sole purpose.

const _ = require('lodash')

let escapedString = _.escapeRegExp('[lodash](https://lodash.com/)')

console.log(escapedString)
// => '\[lodash\]\(https://lodash\.com/\)'

Construct Regular Expression object from string:

let re = new RegExp(escapedString)

let match = re.exec('Should only match [lodash](https://lodash.com/)')
console.log(match)
// [
//   '[lodash](https://lodash.com/)',
//   index: 18,
//   input: 'Should only match [lodash](https://lodash.com/)',
//   groups: undefined
// ]
// => match[0] is the matched string

Bonus: should you only need the escape feature and don’t wish to include Lodash library to your code, the simple function below is sufficient:

(more…)

Common text case conversion in JavaScript

change-case NPM package includes many text conversion methods for most common cases: camel case, capital case, constant case, dot case, header case, no case, param case, pascal case, path case, sentence case, and snake case. It’s very easy to use, see example:

const changeCase = require('change-case')

const input = 'An_Example string-with.mixed CASES 11.12-2020.. @ #$ %^  & * ('

console.log(changeCase.camelCase(input))
// => anExampleStringWithMixedCases_11_12_2020

console.log(changeCase.capitalCase(input))
// => An Example String With Mixed Cases 11 12 2020

console.log(changeCase.constantCase(input))
// => AN_EXAMPLE_STRING_WITH_MIXED_CASES_11_12_2020

console.log(changeCase.dotCase(input))
// => an.example.string.with.mixed.cases.11.12.2020

console.log(changeCase.headerCase(input))
// => An-Example-String-With-Mixed-Cases-11-12-2020

console.log(changeCase.noCase(input))
// => an example string with mixed cases 11 12 2020

console.log(changeCase.paramCase(input))
// => an-example-string-with-mixed-cases-11-12-2020

console.log(changeCase.pascalCase(input))
// => AnExampleStringWithMixedCases_11_12_2020

console.log(changeCase.pathCase(input))
// => an/example/string/with/mixed/cases/11/12/2020

console.log(changeCase.sentenceCase(input))
// => An example string with mixed cases 11 12 2020

console.log(changeCase.snakeCase(input))
// => an_example_string_with_mixed_cases_11_12_2020

Find duplications in array using Lodash (JavaScript)

Lodash is my favorite JavaScript library that includes many useful data manipulation utilities in functional programming style. It can run in Node.js and browsers.

The below snippet is an example of using 2 functions filter and includes to find duplications in an array.

const _ = require('lodash')

const values = [1,2,2,3,4,1]
const duplications = _.filter(values, (value, i) => {
 return _.includes(values, value, i + 1)
})

console.log(duplications) 
// => [1, 2]

Explain:

(more…)