tech

Pure function to shuffle an array in Typescript using fp-ts

A pure function that allows you to shuffle an array using functional programming with fp-ts in Typescript.


Sandro Maglione

Sandro Maglione

Software development

This is a pure function (without side-effects) that allows you to shuffle a given array in Typescript. The code uses fp-ts for the IO type.

shuffle.ts
import * as IO from 'fp-ts/IO';

/** Shuffle randomly the given array, algorithm from https://stackoverflow.com/a/12646864/7033357 */
export const shuffle =
  <T>(array: T[]): IO.IO<T[]> =>
  () => {
    const source = [...array];
    for (let i = source.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [source[i], source[j]] = [source[j], source[i]];
    }

    return source;
  };

👋・Interested in learning more, every week?

Timeless coding principles, practices, and tools that make a difference, regardless of your language or framework, delivered in your inbox every week.