ananoid 1.1.0

Edit this page

How-To: Work with NanoId strings

Ananoid can serve most uses cases via the NanoId type and its associates (Alphabet, et cetera). However, sometimes this is not desired (or at least, not optimal). For times when the a struct or class is just too much, Ananoid also provides its core functionality -- cryptographically-secure randomly-generated identifiers -- as functions which take simple inputs and just produce strings.

These primitive functions are located in the Core module, and offer two variants: one based on default values, and one which allows customizing both alphabet and size. The following example demonstrates:

F#
open pblasucci.Ananoid.Core

let defaultId = nanoId ()
// ⮝⮝⮝ These two call do the same thing. ⮟⮟⮟
let urlSafeId = nanoIdOf Defaults.Alphabet Defaults.Size

printfn $"%s{nameof defaultId}: %s{defaultId}"
printfn $"%s{nameof urlSafeId}: %s{urlSafeId}"

let alphabet, size = ("0123456789", 42)
let numericId = nanoIdOf alphabet size

printfn $"%s{nameof numericId}: %s{numericId}"
VB
Imports static pblasucci.Ananoid.Core

Dim defaultId = NewNanoId()
' ⮝⮝⮝ These two call do the same thing. ⮟⮟⮟
Dim urlSafeId = NewNanoId(Defaults.Alphabet, Defaults.Size)

WriteLine($"{NameOf(defaultId)}: {defaultId}")
WriteLine($"{NameOf(urlSafeId)}: {urlSafeId}")

Dim numericId = NewNanoId(alphabet:="0123456789", size:=42)

WriteLine($"{NameOf(numericId)}: {numericId}")
C#
using static pblasucci.Ananoid.Core

val defaultId = NewNanoId();
// ⮝⮝⮝ These two call do the same thing. ⮟⮟⮟
val urlSafeId = NewNanoId(Defaults.Alphabet, Defaults.Size);

WriteLine($"{nameof(defaultId)}: {defaultId}");
WriteLine($"{nameof(urlSafeId)}: {urlSafeId}");

val numericId = NewNanoId(alphabet: "0123456789", size: 42);

WriteLine($"{nameof(numericId)}: {numericId}");
OUT
> dotnet fsi ~/scratches/nanoidstring.fsx

defaultId: StsrpEEfFWnoSSUqB0IyM
urlSafeId: Yg6PLr0_l2P6IsWgsMh3w
numericId: 176645656821584823660920061658558763998443

Related Reading

Copyright

The library is available under the Mozilla Public License, Version 2.0. For more information see the project's License file.

val defaultId: string
val urlSafeId: string
val printfn: format: Printf.TextWriterFormat<'T> -> 'T
val nameof: 'T -> string
val alphabet: string
val size: int
val numericId: string