1.0.9 • Published 12 months ago
list-map-ts v1.0.9
list-map-ts project
This project provides Java-like List and Map functionalities
- Install
- Import
- List
- add()
- size()
- isEmpty()
- contains()
- remove() - removes an element from list
- clear() - removes all elements from the list
- get() - gets an element by index
- toArray() - converts the list to an array
- arrayToList() - converts a provided array to list
- forEach() - loops through the entire list
- where() - returns all the elements from the collection which satisfy a given condition.
- orderBy() - returns an array ordered by the specified property in either descending or ascending order
Usage:
step1: install
npm i list-map-ts
step2: import
import {KeyValueMap, List} from "list-map-ts";
a model to provide an object blue print
// a model
interface IUser {
id: number
email: string;
name: string
}
// this helps to create a new user instance/object
const newUserObject = (u?: Partial<IUser>): IUser => {
const defaults: IUser = {
id: 0,
name: '',
email: ''
}
return {
...defaults,
...u
}
}
List
instantiate list
// initialize list
const list = new List<IUser>()
add to list
// 1. add to list
list.add(newUserObject({id: 1, name: 'Daniel', email: 'daniel@example.com'}))
list.add(newUser({id: 2, name: ' Adam', email: 'adam@mail.com'}))
size of list
show how many elements are in list
//
const size = list.size()
console.log(size) // prints 2
check if list is empty
console.log(list.isEmpty()) // prints false
check if list contains
const flag = list.contains(newUser({id: 1, name: ' Daniel', email: 'danie@mail.com'}))
console.log(flag) // prints true
forEach loop
list.forEach((item: IUser, index: number) => {
console.log(item, index)
})
where condition
const t = list.where(item => item.email.includes('danie'))
console.log(t) // produces [ { id: 1, name: ' Daniel', email: 'danie@mail.com' } ]
orderBy
const t = list.orderBy('name', true)
console.log(t)
/**
* prints
*
[
{ id: 2, name: ' Adam', email: 'adam@mail.com' },
{ id: 1, name: ' Daniel', email: 'danie@mail.com' }
]
*/