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

@arcaelas/collection

v2.1.2

Published

Searching, filtering and mapping collections is the bread and butter for developers, that's why we offer you "eloquent".

Downloads

58

Readme

Arcaelas Insiders Banner

Arcaelas Insiders Banner

Welcome to Arcaelas Insiders!

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

Implementation

// Class Import Statement
import Collection from  '@arcaelas/Collection'

// Function import statement
import { Collection } from  '@arcaelas/collection'

// EsModule
const Collection =  require('@arcaelas/collection')

Motivation

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".

Curiosities

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.

Get Started

import Collection from "@arcaelas/collection"

const collection = new Collection([ ... ])

filter()

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"]
		}
	}
});

not()

Get all elements that not matched with expression or handler.

users.filter({
	online: { $not: false }
})
user.not({
	online: false
})

first()

Get first matched element, using QueryHandler

users.first({
	_id: "...",
	age:{ $gte: 18 },
	role:{
		$not:{
			$in:["admin"]
		}
	}
})

last()

Get last matched element, using QueryHandler

users.last({
	_id: "...",
	age:{ $gte: 18 },
	role:{
		$not:{
			$in:["admin"]
		}
	}
})

where()

Use this shorthand to filter items

const offline = users.where("online", false)
const online = users.where("online", "==", false)

whereNot()

Is opposite of where()

const offline = users.whereNot("online", true)
const online = users.whereNot("online", "==", true)

update()

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
})

delete()

Remove matched elementos from collection NOTE: This method mutate collection

// Remove all elements where "deletedAt" is not "nullable"
collection.delete({
	deletedAt: {
		$exists: true
	}
})

collect()

Create a collection with parent collection prototypes.

collection.collect([...]) // Expected: Collection

dd()

The dd method will console.log the collection and exit the current process

collection.dd()
// Collection { items: [ 1, 2, 3 ] }
// (Exits node.js process)

dump()

Print collection and continue.

collection.dump()

max()

The max method returns the maximum value of a given key.

pictures.max("upvotes")

min()

The min method returns the minimum value of a given key.

pictures.min("upvotes")

random()

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

shuffle()

This method set items order as random and mutate collection.

collection.shuffle()

sum()

Sum the elements values according to a specific key.

const to_pay = shop_cart.sum("articles.price")

chunk()

Break the collection into multiple, smaller collections of a given size.

paginate = posts.chunks(100)

countBy()

Group items by key and count

products.countBy("buyed")

each()

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")
})

forget()

Remove a specific fields from each items

	sessions.forget("access_token")

groupBy()

Group items by key

const online = followers.grupBy("online") // { ... }
const offline = online.false

paginate()

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

unique()

Filter elements and return only elements that key/value is unique.

const unlinked = links.unique("_id")
const removed = trash.unique((item)=>{
	return item.id
})

macro()

Adding custom methods for current collection.

collection.macro("getName", (item)=>{
	return item.name
}) // Expected: Collection

collection.getName() // Expected: [ Joe, Julia, ... ]

sort()

The sort method sorts the collection.

collection.sort((a, b)=> a.age > b.age ? 1 : -1)
// or
collection.sort("age", "desc")

every()

"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"
})

macro (static)

Adding custom method for all Collections

Collection.macro("get", (item, key)=>{...})

const pictures = new Collection([...])

pictures.get("url") // Expected: [...]

concat

Read Array.prototype.concat

map

Read Array.prototype.map

pop

Read Array.prototype.pop

slice

Read Array.prototype.slice

splice

Read Array.prototype.splice

shift

Read Array.prototype.shift

unshift

Read Array.prototype.unshift

¿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.