PieterVanPoyer / ts-array-collection

Manage array data as collection

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Ts Array Collection

npm version

ArrayCollection extends native Javascript Array and adds additional methods to manage Array data as a collection.

Features

  • ArrayCollection is still a native Javascript Array under the hood (all Array methods stay intact, ES6 Array spread syntax still works)
  • Every ArrayCollection method returns a new ArrayCollection/Array which is useful if you need to work with immutable data

Usage

Create a new Array Collection:

const collection: ArrayCollection<T> = new ArrayCollection(obj1, obj2);

Update Arrays with following methods:

add(item: T): ArrayCollection<T>

update(item: T): ArrayCollection<T>

remove(id: string | number): ArrayCollection<T>

set(items: T[]): ArrayCollection<T>

Example

import { ArrayCollection } from 'ts-array-collection';

class Todo {
  id: number;
  title: string;
  desc?: string;
}

const collection: ArrayCollection<Todo> = new ArrayCollection();
const added: ArrayCollection<Todo> = collection.add({
  id: 1,
  title: 'Todo 1'
});

console.log('added', added);

const updated: ArrayCollection<Todo> = collection.update({
  id: 1,
  title: 'Todo 1',
  desc: 'Updated Desc'
});

console.log('updated', updated);

Console output:

Example

ArrayCollection uses the id property of an item to find the correct item e.g. for update/remove. The default idKey can be adjusted:

const collection: ArrayCollection = new ArrayCollection().setIdKey('fancyId')

License

MIT

Created By

If you like this, follow @spierala on twitter.

About

Manage array data as collection


Languages

Language:TypeScript 84.2%Language:JavaScript 15.8%