| 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 |
|
||||||
| rule |
|
||||||
| related |
|
||||||
| author | PaulJPhilp | ||||||
| lessonOrder | 24 |
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.
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.
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.arraycreates 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.
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.