---
sidebar_position: 1
title: Random
comment: true
tags:
  - Javascript
  - 1loc
  - Random
---

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

## Generate a random integer in given range

<Tabs>
  <TabItem value='js' label='Javascript' default>

```js
const randomInteger = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
```

  </TabItem>
  <TabItem value='ts' label='Typescipt'>

```ts
const randomInteger = (min: number, max: number): number =>
  Math.floor(Math.random() * (max - min + 1)) + min;
```

  </TabItem>
</Tabs>

## Sort an object by its properties

<Tabs>
  <TabItem value='js' label='Javascript' default>

```js
const sort = (obj) =>
  Object.keys(obj)
    .sort()
    .reduce((p, c) => ((p[c] = obj[c]), p), {});

// Example
const colors = {
  white: '#ffffff',
  black: '#000000',
  red: '#ff0000',
  green: '#008000',
  blue: '#0000ff',
};
sort(colors);
/*
{
    black: '#000000',
    blue: '#0000ff',
    green: '#008000',
    red: '#ff0000',
    white: '#ffffff',
}
*/
```

  </TabItem>
</Tabs>

## Generate a random hex color

<Tabs>
  <TabItem value='js' label='Javascript' default>

```js
const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`;

// Or
const randomColor = () => `#${(~~(Math.random() * (1 << 24))).toString(16)}`;
```

  </TabItem>
  <TabItem value='ts' label='Typescipt'>

```ts
const randomColor = (): string => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`;

// Or
const randomColor = (): string => `#${(~~(Math.random() * (1 << 24))).toString(16)}`;
```

  </TabItem>
</Tabs>

## Generate a random string from given characters

<Tabs>
  <TabItem value='js' label='Javascript' default>

```js
const generateString = (length, chars) =>
  Array(length)
    .fill('')
    .map((v) => chars[Math.floor(Math.random() * chars.length)])
    .join('');
```

  </TabItem>
  <TabItem value='ts' label='Typescipt'>

```ts
const generateString = (length: number, chars: string) =>
  Array(length)
    .fill('')
    .map((v) => chars[Math.floor(Math.random() * chars.length)])
    .join('');
```

  </TabItem>
</Tabs>

## Generate a random UUID

<Tabs>
  <TabItem value='js' label='Javascript' default>

```js
const uuid = (a) =>
  a
    ? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16)
    : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, uuid);
```

  </TabItem>
</Tabs>
