npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@dougwithseismic/magicarray

v1.0.2

Published

Adds a ton of actually useful methods to an Array, because it's worth it.

Downloads

4

Readme

MagicArray

MagicArray is a TypeScript library designed to provide extensive array manipulation features, extending the traditional array functionality with added operations and validation support. It comes with a unique history tracking system and enables an extra level of validation and manipulation for array data structures.

Table of Contents

  1. Installation
  2. Features
  3. Array Methods
  4. History Actions
  5. Usage Examples
  6. License

Installation

Install MagicArray using npm:

npm install @dougwithseismic/magicarray

Or using yarn:

yarn add @dougwithseismic/magicarray

Usage

import createMagicArray  from '@dougwithseismic/magicarray';

Features

  • Array Manipulation: Perform standard and custom array operations.
  • Validation Support: Enforce rules with validation functions.
  • Serialization and Deserialization: Easily convert arrays to JSON strings and back.
  • History Tracking: Track changes, undo, redo, save checkpoints, and navigate history.
  • Batch Operations: Conduct batch operations like batch push.

Array Methods

MagicArray supports all standard JavaScript array methods, enhancing them with additional capabilities.

Custom Methods

batchPush(itemsToPush: T[]): void

Batch push items into the array.

Example
const magicArray = createMagicArray<number>();
magicArray.batchPush([4, 5, 6]);

search(queryFn: (item: T) => boolean): T[]

Search the array using a query function.

Search Example
const magicArray = createMagicArray<number>();
const result = magicArray.search(item => item > 2);

setValidation(fn: ValidationFunction<T>): void

Set a validation function to filter items.

setValidation Example
const magicArray = createMagicArray<number>();
magicArray.setValidation(item => item > 0);

serialize(): string

Serialize the current array into a JSON string.

serialize Example
const magicArray = createMagicArray<number>();
const jsonString = magicArray.serialize();

deserialize(jsonString: string): void

Deserialize a JSON string into the current array.

Example
const magicArray = createMagicArray<number>();
magicArray.deserialize(jsonString);

getItems(): T[]

Retrieve a shallow copy of the items in the array.

Example
const magicArray = createMagicArray<number>();
const items = magicArray.getItems();

Standard Methods

The library supports all standard JavaScript array methods, enhancing them with additional capabilities.

History Actions

MagicArray comes with a history system to track changes and enable navigation through past states. Here are the functionalities:

previous(): T[]

Navigate to the previous state in history.

Example

const prevState = magicArray.history.previous();

next(): T[]

Navigate to the next state in history.

Example

const nextState = magicArray.history.next();

clean(): void

Clean the history by resetting it.

Example

magicArray.history.clean();

jump(number: number): T[]

Jump by a specified number of steps in the history.

Example

magicArray.history.jump(2);

goTo(index: number): T[]

Go to a specific index in the history.

Example

magicArray.history.goTo(5);

saveCheckpoint(label?: string): void

Save a checkpoint with an optional label.

Example

magicArray.history.saveCheckpoint('before-change');

restoreCheckpoint(label: string): void

Restore a checkpoint by its label.

Example

magicArray.history.restoreCheckpoint('before-change');

listCheckpoints(): Checkpoint<T>[]

List all checkpoints.

Example

const checkpoints = magicArray.history.listCheckpoints();

toJSON(): string

Convert the history to a JSON string.

Example

const jsonHistory = magicArray.history.toJSON();

toCSV(delimiter: string): string

Convert the history to a CSV string with a given delimiter.

Example

const csvHistory = magicArray.history.toCSV(';');

import(serialized: string): void

Import a serialized string to replace the current history.

Example

magicArray.history.import(serializedHistory);

limit(size: number): void

Limit the size of the history, removing older entries if necessary.

Example

magicArray.history.limit(10);

hasChanges(): boolean

Check if there are any changes in the current state compared to the history.

Example

const changes = magicArray.history.hasChanges();

subscribe(listener: HistoryChangeListener): void

Subscribe a listener to changes in the history.

Example

magicArray.history.subscribe(listener);

undo(times?: number): void

Undo a specified number of changes, or one change if no number is provided.

Example

magicArray.history.undo(3);

redo(times?: number): void

Redo a specified number of changes, or one change if no number is provided.

Example

magicArray.history.redo(3);

Usage Examples

For Game Development

Managing game states and allowing players to undo and redo actions:

const gameState = createMagicArray<Game>();
gameState.history.saveCheckpoint('level-1');
// Player makes moves...
gameState.history.undo(); // Undo last move

For Task Management

Managing tasks in a project with the ability to track the changes, undo/redo task updates, and save checkpoints:

const tasks = createMagicArray<Task>();
tasks.batchPush([
  { title: 'Write code', status: 'done' },
  { title: 'Write tests', status: 'in-progress' }
]);
tasks.history.saveCheckpoint('initial-tasks');
tasks.search(task => task.status === 'in-progress'); // Search tasks in progress
tasks.history.undo(); // Undo the last change

For User Profile Management

Handling user profiles and tracking changes, making it easy to revert to previous states:

const users = createMagicArray<UserProfile>();
users.setValidation(user => user.age > 18); // Validate user's age
users.batchPush(newUserProfiles);
users.history.saveCheckpoint('after-new-users');
// Make updates...
users.history.restoreCheckpoint('after-new-users'); // Restore to previous state

For Shopping Cart Management

Manipulating shopping cart items, searching for products, and maintaining history checkpoints:

const cart = createMagicArray<Product>();
cart.batchPush(selectedProducts);
cart.search(product => product.category === 'electronics'); // Search for electronics
cart.history.saveCheckpoint('after-adding-electronics');
// Remove some items...
cart.history.restoreCheckpoint('after-adding-electronics'); // Restore to previous state

For Timeline Creation in Social Media

Building a timeline for social media applications, with features to go back and forth through user posts and actions:

const timeline = createMagicArray<Post>();
timeline.batchPush(newPosts);
timeline.history.next(); // Navigate to the next state in history
timeline.history.previous(); // Navigate to the previous state in history
timeline.history.saveCheckpoint('user-login'); // Save a specific point in time

For Health Data Tracking

Tracking patients' health data with the ability to analyze, search, and maintain historical records:

const patientData = createMagicArray<HealthRecord>();
patientData.search(record => record.condition === 'diabetes'); // Search for diabetic patients
patientData.history.saveCheckpoint('end-of-year'); // Save end-of-year records
// Analyzing data...
patientData.history.restoreCheckpoint('end-of-year'); // Restore to end-of-year state

For Configuration Management

Saving and restoring configurations:

const config = createMagicArray<Config>();
config.history.saveCheckpoint('stable');
// Make changes...
config.history.restoreCheckpoint('stable'); // Restore to stable

Obstacle Avoidance and Path Planning for Drone Swarms

Planning and adjusting paths for a swarm of drones to avoid obstacles, with the ability to revert to previous paths:

const obstacleAvoidancePaths = createMagicArray<Path>();
obstacleAvoidancePaths.setValidation(path => !path.hasObstacle); // Validate paths without obstacles
obstacleAvoidancePaths.batchPush(plannedPaths);
obstacleAvoidancePaths.history.saveCheckpoint('obstacle-free');
// Replan paths if new obstacles are detected...
obstacleAvoidancePaths.history.restoreCheckpoint('obstacle-free'); // Revert to obstacle-free paths

Synchronized Movement of Drone Swarm

Synchronizing the movement of a swarm of drones by batch updating waypoints and saving key checkpoints:

const swarmWaypoints = createMagicArray<DroneSwarm>();
swarmWaypoints.batchPush(swarmFormation1);
swarmWaypoints.history.saveCheckpoint('formation-1');
swarmWaypoints.batchPush(swarmFormation2);
swarmWaypoints.history.saveCheckpoint('formation-2');
// Transition between formations...
swarmWaypoints.history.restoreCheckpoint('formation-1'); // Restore to formation 1

... You get the picture.

License

MagicArray is MIT licensed.