Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript generates a unique ID


May 09, 2021 CoffeeScript


Table of contents


Build a unique ID

Problem

You want to randomly generate a unique identifier.

Solution

A Base 36 encoded string can be generated from a random number.

uniqueId = (length=8) ->
  id = ""
  id += Math.random().toString(36).substr(2) while id.length < length
  id.substr 0, length

uniqueId()    # => n5yjla3b
uniqueId(2)   # => 0d
uniqueId(20)  # => ox9eo7rt3ej0pb9kqlke
uniqueId(40)  # => xu2vo4xjn4g0t3xr74zmndshrqlivn291d584alj

Discuss

Other techniques are also available, but this approach is relatively more performance-effective and flexible.