Hello, if this is your first time reading the Arcaelas Insiders documentation, let me tell you that you have found a good place to learn.
Our team and community are happy to write and make methods simple to implement and understand, but I think you already know that.
The documentation for this tool is open to edits and suggestions.
Let's start with the basic implementation steps.
> npm i --save @arcaelas/collection
> yarn add --save @arcaelas/collection
// Class Import Statement
import Collection from '@arcaelas/Collection'
// Function import statement
import { Collection } from '@arcaelas/collection'
// EsModule
const Collection = require('@arcaelas/collection')
In object-oriented programming we find common situations, such as those where we want to order, filter and modify elements of a list, however the "Array Prototypes" are not very complete in some cases, for these situations the Arcaelas Insiders team has designed useful tools that allow these actions within "Collections".
As an interesting part of this tool, we have the B-JSON notation that Atlas implements in its MongoDB database engine, only some of them are implemented here, but we will explain how to extend them and create your own validators.
import Collection from "@arcaelas/collection"
const collection = new Collection([ ... ])
All matched elements fro collection, you can use callback or QueryHandler:
// Using callback to filtering...
collection.filter(item=>{
return item.age >= 18;
});
// or match expressions...
collection.filter({
age:{ $gte: 18 }
});
// veteran level.
collection.filter({
name: /Alejandro/,
skills:{
$contains: "Liberty"
},
gender:{
$not:{
$in: ['animal','fruit'],
}
},
work:{
$not:{
$in: ["work", "without", "coffe"]
}
}
});
Get all elements that not matched with expression or handler.
users.filter({
online: { $not: false }
})
user.not({
online: false
})
Get first matched element, using QueryHandler
users.first({
_id: "...",
age:{ $gte: 18 },
role:{
$not:{
$in:["admin"]
}
}
})
Get last matched element, using QueryHandler
users.last({
_id: "...",
age:{ $gte: 18 },
role:{
$not:{
$in:["admin"]
}
}
})
Use this shorthand to filter items
const offline = users.where("online", false)
const online = users.where("online", "==", false)
Is opposite of where()
const offline = users.whereNot("online", true)
const online = users.whereNot("online", "==", true)
Updates information for items that match a specific or general filter expression.
// Simple matches
// Update all elements that "online" field is false
// Add or replace "deletedAt" field with "new Date()"
collection.update({ online: false }, { deletedAt: new Date() })
// Most common
collect.update({
email: /gmail\.com$/g // all items that email is Gmail Host
}, {
email: null, // Set current email to null
prevEmail: "${email}" // Save email in this field
})
Remove matched elementos from collection NOTE: This method mutate collection
// Remove all elements where "deletedAt" is not "nullable"
collection.delete({
deletedAt: {
$exists: true
}
})
Create a collection with parent collection prototypes.
collection.collect([...]) // Expected: Collection
The dd method will console.log the collection and exit the current process
collection.dd()
// Collection { items: [ 1, 2, 3 ] }
// (Exits node.js process)
Print collection and continue.
collection.dump()
The max method returns the maximum value of a given key.
pictures.max("upvotes")
The min method returns the minimum value of a given key.
pictures.min("upvotes")
Get random elements, with the argument "length" the number of elements is indicated.
collection.random() // All elements random sorted
collection.random(2) // Two random elements
This method set items order as random and mutate collection.
collection.shuffle()
Sum the elements values according to a specific key.
const to_pay = shop_cart.sum("articles.price")
Break the collection into multiple, smaller collections of a given size.
paginate = posts.chunks(100)
Group items by key and count
products.countBy("buyed")
Iterate over each collection elements, if return false break iteration
sockets.each(socket=>{
if( !socket.online ) return false// This stop iteration
else if( socket.name ) return // Iteration skip current cycle, not stoped.
socket.send("ping")
})
Remove a specific fields from each items
sessions.forget("access_token")
Group items by key
const online = followers.grupBy("online") // { ... }
const offline = online.false
Wrap element in X number of items and return specific page.
const page_one = post.paginate(1) // 1 - 20
const page_two = post.paginate(2, 500) // 501 - 1000
Filter elements and return only elements that key/value is unique.
const unlinked = links.unique("_id")
const removed = trash.unique((item)=>{
return item.id
})
Adding custom methods for current collection.
collection.macro("getName", (item)=>{
return item.name
}) // Expected: Collection
collection.getName() // Expected: [ Joe, Julia, ... ]
The sort method sorts the collection.
collection.sort((a, b)=> a.age > b.age ? 1 : -1)
// or
collection.sort("age", "desc")
"Every" can verify that all elements satisfy a certain expression. Read Array.prototype.every
// Check if every items have "_id" field
collection.every('_id')
// All items have "status" == "enabled"
collection.every('status', 'enabled')
// All prices items is greater than zero "0"
collection.every('price', '>', 0)
// Using QueryHandler to match every items.
collection.every({
expired: { $not: true } // All "expired" items is ddifferent that "true"
})
Adding custom method for all Collections
Collection.macro("get", (item, key)=>{...})
const pictures = new Collection([...])
pictures.get("url") // Expected: [...]
Read Array.prototype.map
Read Array.prototype.pop
¿Want to discuss any of my open source projects, or something else?Send me a direct message on Twitter.
If you already use these libraries and want to support us to continue development, you can sponsor us at Github Sponsors.