Intent
Interface for managing collections of items.
Installation & Usage
npm i @lbzg/collections
import { collection } from '@lbzg/collections'
class Item {
constructor(public id: number) {}
}
const store = collection<Item>(Item)
store.config.size(10)
store.hook.add(console.log)
store.add(new Item(1)) # true ~ c.logs item 1
store.add([new Item(11), new Item(22)]) # true ~ c.logs item 11, c.logs item 22
store.create(33) # true ~ c.logs item 33
store.get(1) # item 1
store.get(25) # undefined
store.get([0, 22, 11]) # item 22
store.get(x => x.id < 100) # item 1
store.getAll() # [item 1, item 11, item 22, item 33]
store.getAll(1) # [item 1]
store.getAll([1, 22]) # [item 1, item 22]
store.getAll(x => x.id < 20) # [item 1, item 11]
store.remove(1) # true ~ removes item 1
store.remove([1, 11]) # true ~ removes item 11
store.remove(x => x.id === 22) # true ~ removes item 22
store.has(33) # true
store.count() # 1
store.list() # [33]
store.usage() # 0.1 ~ current size / config size (10)
store.clear() # void
Prototype
Exports collection
factory function and ICollection
interface.
collection(ctor?, key?) ~ limits insertion to ctor class if provided
key ~ object identifier; defaults to 'id'
METHODS
add(
input
): boolean ~ true if any added
remove(selector
): boolean ~ true if any removed
create(...args?): boolean ~ true if created and added (uses ctor or factory)
clear(): void ~ empties the collection
ap ::
fn
->selector
-> void
apTo ::selector
->fn
-> void
apFn
:: item -> any
get(
selector
): entry | null
getAll(selector
?): array
count(selector
?): number
has(selector
?): boolean ~ all for value or value[]; any for cb
list(key?): array ~ lists collection items property
usage(): number ~ currentSize/configSize
input
~ value | value[]
selector
~ value | value[] | filter function
Selector as value ~ selects values or objects (by identifier value)
CONFIG (collection.config)
size(num) ~ collection size (enables usage method)
strict(bool) ~ strict size / restrict adding above limit
unique(bool) ~ allow unique values / objects
factory(fn
) ~ factory function for create method
validator(fn
) ~ insertion validation
validatorFn
:: item -> boolean
factoryFn
:: (...args) -> item
HOOKS (collection.hook)
add(
fn
?) ~ triggered on added/created items
remove(fn
?) ~ triggered on removed items
clear(fn
?) ~ triggered on cleared items
hookFn
:: item -> any