Skip to content

Latest commit

 

History

History
69 lines (54 loc) · 2.15 KB

File metadata and controls

69 lines (54 loc) · 2.15 KB
title Working with Immutable Arrays using Data.array
id data-array
skillLevel beginner
applicationPatternId core-concepts
summary Use Data.array to create immutable, type-safe arrays that support value-based equality and safe functional operations.
tags
Data.array
array
structural-equality
immutable
data-type
effect
rule
description
Use Data.array to define arrays whose equality is based on their contents, enabling safe, predictable comparisons and functional operations.
related
use-chunk-for-high-performance-collections
data-struct
data-tuple
author PaulJPhilp
lessonOrder 24

Working with Immutable Arrays using Data.array

Guideline

Use Data.array to create immutable, type-safe arrays that support value-based equality and safe functional operations.
This is useful for modeling ordered collections where immutability and structural equality are important.

Rationale

JavaScript arrays are mutable and compared by reference, which can lead to bugs in value-based logic and concurrent code.
Data.array provides immutable arrays with structural equality, making them ideal for functional programming and safe domain modeling.

Good Example

import { Data, Equal } from "effect";

// Create two structurally equal arrays
const arr1 = Data.array([1, 2, 3]);
const arr2 = Data.array([1, 2, 3]);

// Compare by value, not reference
const areEqual = Equal.equals(arr1, arr2); // true

// Use arrays as keys in a HashSet or Map
import { HashSet } from "effect";
const set = HashSet.make(arr1);
console.log(HashSet.has(set, arr2)); // true

// Functional operations (map, filter, etc.)
const doubled = arr1.map((n) => n * 2); // Data.array([2, 4, 6])

Explanation:

  • Data.array creates immutable arrays with value-based equality.
  • Useful for modeling ordered collections in a safe, functional way.
  • Supports all standard array operations, but with immutability and structural equality.

Anti-Pattern

Using plain JavaScript arrays for value-based logic, as keys in sets/maps, or in concurrent code, which can lead to bugs due to mutability and reference-based comparison.