random typescript functions I use for mocking data
By Per Fröjd
- snippets
- typescript
Why
I find myself needing to mock data more often than not, and it’s a good way to test out the boundaries of elements and other things. I shouldn’t need to explain more really,
sometimes you need to randomize the order of output, sometimes you just need very long output and sometimes you don’t even have any data at all to work with.
To stop myself from googling the same random element from array
result, I can just put the snippets here instead.
Getting a random value between
Simple, return a random number between min and max, it’s often a useful foundation for a lot of these.
export function randomBetween(min: number, max: number) {
return Math.floor(Math.random() * (max - min + 1) + min)
}
Generating input
NOTE: Do note that this uses the above randomBetween
function.
This code will generate a bunch of garbled text, including all sorts of symbols and spaces (if includeSpaces
remains true). This isn’t really a replacement for Lorem Ipsum, since that has got a nice mix of short and long words, where as this implementation is very likely to create very long inputs with very few spaces.
One could quite easily make sure that the spaces are randomized with a different weighting to be included more often.
export function getTestInput({
length,
includeSpaces = true,
}: {
length: number
includeSpaces?: boolean
}) {
const START_OF_CHARACTERS = includeSpaces ? 32 : 33
const END_OF_CHARACTERS = 126
return Array.from({ length: length })
.map(() => {
const randomCharacter = randomBetween(
START_OF_CHARACTERS - 1,
END_OF_CHARACTERS
)
return String.fromCharCode(randomCharacter)
})
.join('')
}
Picking a random value from a list
Not much to add here, sometimes you just want to pick something randomly from a list.
export function randomChoice<T>(list: Array<T>) {
return list[Math.floor(Math.random() * list.length)]
}
Filling an array with something
export function fillArrayWith<T>(amount: number, fn: () => T) {
return Array.from({ length: amount + 1 }).map((_) => fn())
}
Simulating a delay
export function sleep(time: number) {
return new Promise((resolve) => setTimeout(resolve, time))
}
Bonus - Files and node.js
A bit of a bonus, but sometimes you end up needing to process a bunch of files in node (with typescript, preferably). Maybe you end up needing to do some operations on each files of a folder, or maybe you’re like me and haven’t gotten comfortable with bash, and decide to use node for some filesystem based scripts. There’s also plenty of packages on NPM that solve this, which are probably better than this.
This will simply deliver an array of all files found within a directory, and its sub-directories.
You should be able to use this in Deno too, by replacing readdir
and stat
with their Deno equivalents, Deno.readDir
and Deno.stat
. Also the path.join
function needs replacement, Deno.realPath
is probably a good choice there.
import { readdir, stat } from 'node:fs/promises;'
import path from 'node:path'
async function walk(dir: string) {
let files: any = await readdir(dir)
files = await Promise.all(
files.map(async (file: any) => {
const filePath = path.join(dir, file)
const stats = await stat(filePath)
if (stats.isDirectory()) return walk(filePath)
else if (stats.isFile()) return filePath
})
)
return files.reduce(
(all: any, folderContents: any) => all.concat(folderContents),
[]
)
}