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

Sandro Maglione

Sandro Maglione

Web 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.

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?

Every week I build a new open source project, with a new language or library, and teach you how I did it, what I learned, and how you can do the same. Join me and other 700+ readers.