CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-polkadot--util

A collection of useful utilities for @polkadot ecosystem with type checking, data conversion, and performance optimization functions

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

arrays.mddocs/

Array Utilities

Functional array manipulation utilities for common operations like chunking, flattening, shuffling, and data transformation in JavaScript/TypeScript applications.

Capabilities

Array Transformation

Core array manipulation functions for transforming array structures.

/**
 * Splits an array into chunks of specified size
 * @param array - Array to split into chunks
 * @param size - Size of each chunk
 */
function arrayChunk<T>(array: T[], size: number): T[][];

/**
 * Flattens a multi-dimensional array into a single dimension
 * @param array - Array containing nested arrays or single values
 */
function arrayFlatten<T>(array: (T | T[])[]): T[];

/**
 * Creates an array of numbers within a specified range
 * @param size - Number of elements to generate
 * @param startAt - Starting number (default: 0)
 */
function arrayRange(size: number, startAt?: number): number[];

/**
 * Randomly shuffles the elements of an array
 * @param array - Array to shuffle
 */
function arrayShuffle<T>(array: T[]): T[];

Array Combination

Functions for combining and manipulating multiple arrays.

/**
 * Zips/combines multiple arrays into tuples
 * @param arrays - Arrays to zip together
 */
function arrayZip<T>(...arrays: T[][]): T[][];

/**
 * Unzips/transposes an array of arrays
 * @param array - Array of arrays to unzip
 */
function arrayUnzip<T>(array: T[][]): T[][];

Array Filtering

Advanced filtering utilities for arrays.

/**
 * Filters an array based on a predicate function
 * @param array - Array to filter
 * @param fn - Predicate function returning boolean
 */
function arrayFilter<T>(array: T[], fn: (value: T, index: number, array: T[]) => boolean): T[];

Usage Examples

Array Chunking:

import { arrayChunk } from "@polkadot/util";

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const chunks = arrayChunk(numbers, 3);
console.log(chunks); // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

// Processing data in batches
const items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const batches = arrayChunk(items, 2);
// Process each batch separately
batches.forEach((batch, index) => {
  console.log(`Batch ${index + 1}:`, batch);
});

Array Flattening:

import { arrayFlatten } from "@polkadot/util";

const nested = [1, [2, 3], 4, [5, [6, 7]], 8];
const flat = arrayFlatten(nested);
console.log(flat); // [1, 2, 3, 4, 5, [6, 7], 8] (one level deep)

// Flattening mixed data
const mixed = ['hello', ['world', 'foo'], 'bar'];
const flattened = arrayFlatten(mixed);
console.log(flattened); // ['hello', 'world', 'foo', 'bar']

Range Generation:

import { arrayRange } from "@polkadot/util";

// Generate 0-based range
const zeroToFour = arrayRange(5);
console.log(zeroToFour); // [0, 1, 2, 3, 4]

// Generate custom start range
const fiveToNine = arrayRange(5, 5);
console.log(fiveToNine); // [5, 6, 7, 8, 9]

// Generate indices for iteration
const indices = arrayRange(10, 1); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Array Shuffling:

import { arrayShuffle } from "@polkadot/util";

const cards = ['A', 'K', 'Q', 'J', '10', '9', '8', '7'];
const shuffled = arrayShuffle([...cards]); // Creates new shuffled array
console.log(shuffled); // Random order: ['Q', '7', 'A', 'J', ...]

// Shuffle while preserving original
const original = [1, 2, 3, 4, 5];
const randomized = arrayShuffle([...original]);
console.log('Original:', original); // [1, 2, 3, 4, 5]
console.log('Shuffled:', randomized); // [3, 1, 5, 2, 4] (random)

Array Zipping:

import { arrayZip } from "@polkadot/util";

const names = ['Alice', 'Bob', 'Charlie'];
const ages = [25, 30, 35];
const cities = ['NYC', 'LA', 'Chicago'];

const combined = arrayZip(names, ages, cities);
console.log(combined);
// [
//   ['Alice', 25, 'NYC'],
//   ['Bob', 30, 'LA'],
//   ['Charlie', 35, 'Chicago']
// ]

// Creating key-value pairs
const keys = ['name', 'age', 'active'];
const values = ['John', 28, true];
const pairs = arrayZip(keys, values);
console.log(pairs); // [['name', 'John'], ['age', 28], ['active', true]]

Array Unzipping:

import { arrayUnzip } from "@polkadot/util";

const tuples = [
  ['Alice', 25, 'NYC'],
  ['Bob', 30, 'LA'],
  ['Charlie', 35, 'Chicago']
];

const [names, ages, cities] = arrayUnzip(tuples);
console.log(names); // ['Alice', 'Bob', 'Charlie']
console.log(ages);  // [25, 30, 35]
console.log(cities); // ['NYC', 'LA', 'Chicago']

Advanced Filtering:

import { arrayFilter } from "@polkadot/util";

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Filter even numbers
const evens = arrayFilter(numbers, (n) => n % 2 === 0);
console.log(evens); // [2, 4, 6, 8, 10]

// Filter with index
const skipFirst = arrayFilter(numbers, (value, index) => index > 0);
console.log(skipFirst); // [2, 3, 4, 5, 6, 7, 8, 9, 10]

// Complex filtering
const users = [
  { name: 'Alice', age: 25, active: true },
  { name: 'Bob', age: 17, active: false },
  { name: 'Charlie', age: 30, active: true }
];

const activeAdults = arrayFilter(users, (user) => user.active && user.age >= 18);
console.log(activeAdults); // [{ name: 'Alice', age: 25, active: true }, ...]

Combining Multiple Array Operations:

import { arrayRange, arrayChunk, arrayShuffle, arrayZip } from "@polkadot/util";

// Create shuffled pairs for a tournament
function createTournamentPairs(playerCount: number) {
  // Generate player numbers
  const players = arrayRange(playerCount, 1); // [1, 2, 3, ..., playerCount]
  
  // Shuffle for random matchups
  const shuffled = arrayShuffle(players);
  
  // Group into pairs
  const pairs = arrayChunk(shuffled, 2);
  
  // Create match objects
  return pairs.map((pair, index) => ({
    match: index + 1,
    player1: pair[0],
    player2: pair[1] || null // Handle odd number of players
  }));
}

const tournament = createTournamentPairs(8);
console.log(tournament);
// [
//   { match: 1, player1: 5, player2: 2 },
//   { match: 2, player1: 7, player2: 1 },
//   { match: 3, player1: 3, player2: 8 },
//   { match: 4, player1: 6, player2: 4 }
// ]

Install with Tessl CLI

npx tessl i tessl/npm-polkadot--util

docs

arrays.md

big-numbers.md

compact.md

data-conversion.md

formatting.md

index.md

objects.md

strings.md

system.md

type-checking.md

tile.json