Skip to content

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.


Software
1 min read

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;
  };

Continue the thread every Wednesday

One focused idea about type-safe software, AI-assisted development, and creative practice.

Free, no spam, unsubscribe anytime. See the privacy policy.

Want to see what arrives? Explore the newsletter