Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Radash Array Utilities: Core Methods and Implementation Breakdown

Tech Sep 8 2

iterate: Sequential Value Transformation

Usage Executes a transformation function repeatedly over a specified number of steps, carrying forward an accumulator value.

Example

import { iterate } from 'radash'

const total = iterate(
  5,
  (accumulator, step) => accumulator + step * 2,
  0
) // Result: 30

Implementation Logic The function initializes an accumulator with the provided starting value. It then runs a loop exactly count times. During each pass, it applies the provided callback (currentValue, iterationIndex) => newValue and updates the accumulator. Once the loop finishes, the final accumulator state is returned. This pattern is useful for chaining calculations or building sequential states without external libraries.

last: Securely Access Terminal Elements

Usage Retrieves the final element of an iterable collection. Returns a fallback value if the collection is empty or undefined.

Example

import { last } from 'radash'

const inventory = ['hammer', 'wrench', 'screwdriver']
const terminalItem = last(inventory) // 'screwdriver'
const safeDefault = last([], 'n/a')  // 'n/a'

Implementation Logic A guard clause checks the collection's length. If valid and populated, it accesses the index at length - 1. Otherwise, it gracefully falls back to the provided defaultValue or undefined. This prevents TypeError exceptions when dealing with dynamic datasets where emptiness cannot be guaranteed.

list: Sequential Array Construction

Usage Generates an array based on a range configuration, supporting custom values, mappers, and step intervals.

Example

import { list } from 'radash'

list(4)                        // [0, 1, 2, 3]
list(2, 6)                     // [2, 3, 4, 5, 6]
list(0, 4, val => 'fixed')     // ['fixed', 'fixed', 'fixed', 'fixed', 'fixed']
list(0, 8, n => n * n, 2)      // [0, 4, 16, 36]

Implementation Logic Under the hood, this delegates to the range generator. It interprets the first argument as either a start index or a total count depending on whether an end boundary is supplied. A mapping function converts raw indices into final output values. Array.from() consumes the generator to materialize the result. Parameters include bounds, a transform mapper, and an optional increment step.

max: Extract Maximum Values

Usage Identifies the object containing the highest numerical attribute within a collection.

Example

import { max } from 'radash'

const scores = [
  { user: 'A', points: 85 },
  { user: 'B', points: 92 },
  { user: 'C', points: 78 }
]

const winner = max(scores, item => item.points)
// { user: 'B', points: 92 }

Implementation Logic When a selector callback isn't provided, elements are compared directly. The helper leverages a reduce-based comparator utility (boil) to traverse the dataset. Each pair evaluates via the selector, retaining the larger counterpart. Returns null if the input is falsy or empty.

min: Extract Minimum Values

Usage Locates the object with the lowest numerical attribute in a given set.

Example

import { min } from 'radash'

const prices = [
  { id: 1, cost: 29.99 },
  { id: 2, cost: 12.50 },
  { id: 3, cost: 45.00 }
]

const cheapest = min(prices, p => p.cost)
// { id: 2, cost: 12.50 }

Implementation Logic Mirrors the maximum extraction strategy but reverses the comparison operator. Utilizes the same reduce-driven traversal to isolate the smallest value according to the projection function. Handles edge cases by returning null for missing inputs.

merge: Attribute Overwrite Consolidation

Usage Combines two arrays by matching elements via a predicate, prioritizing entries from the secondary array.

Example

import { merge } from 'radash'

const baseConfig = [{ key: 'theme', val: 'dark' }]
const updatedConfig = [{ key: 'theme', val: 'light' }]

const resolved = merge(baseConfig, updatedConfig, c => c.key)
// [{ key: 'theme', val: 'light' }]

Implementation Logic Iterates through the primary array using reduce. For each entry, it searches the secondary array for a matching key/value. Upon finding a match, it injects the secondary entry into the accumulator; otherwise, it retains the original. Returns early if either collection or the matcher function is absent.

objectify: Index-to-Dictionary Conversion

Usage Transforms an array of objects into a lookup map (key-value dictionary).

Example

import { objectify } from 'radash'

const items = [
  { sku: 'A01', stock: 50 },
  { sku: 'B02', stock: 12 }
]

const lookup = objectify(items, i => i.sku)
// { 'A01': { sku: 'A01', stock: 50 }, 'B02': ... }

const counts = objectify(items, i => i.sku, i => i.stock)
// { 'A01': 50, 'B02': 12 }

Implementation Logic Applies reduce to accumulate a plain object. The key extractor defines property identifiers, while an optional value extractor determines payload content. Defaults to assigning the entire object as the value. Strict typing ensures key constraints align with standard JavaScript object keys.

range: Lazy Numerical Sequencing

Usage Produces a generator yielding numbers across a defined span, supporting custom mappings and intervals.

Example

import { range } from 'radash'

const seq1 = [...range(3)]           // [0, 1, 2, 3]
const seq2 = [...range(5, 9)]        // [5, 6, 7, 8, 9]
const seq3 = [...range(0, 6, n => `x${n}`, 2)] // ['x0', 'x2', 'x4', 'x6']

for (const val of range(10, 20, n => n * 10)) {
  console.log(val) // 100, 200, ... 200
}

Implementation Logic Configures start and stop boundaries dynamically based on argument presence. Normalizes scalar payloads into constant-returning functions. Executes a bounded loop yielding transofrmed indices on-demand. The explicit break condition handles inclusive boundaries safely without overflowing the sequence.

replaceOrAppend: Conditional Element Injection

Usage Updates an existing record if a matcher succeeds, or appends a new entry otherwise.

Example

import { replaceOrAppend } from 'radash'

const roster = [
  { role: 'dev', level: 'senior' },
  { role: 'pm', level: 'lead' }
]

const candidate = { role: 'pm', level: 'director' }
const newcomer = { role: 'qa', level: 'junior' }

replaceOrAppend(roster, candidate, r => r.role === 'pm')
// Updates PM role to director

replaceOrAppend(roster, newcomer, r => r.role === 'designer')
// Appends QA role

Implementation Logic Validates input integrity before proceeding. Scans the target array linearly applying the predicate. A hit triggers splicing: preceding elements, the new object, and succeeding elements are concatenated into a fresh array. Exhaustion of the scan results in straightforward concatenation. Ensures immutability by never mutating the original reference.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.