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

@locustjs/extensions-object

v2.2.1

Published

This library contains extension methods for Object

Downloads

136

Readme

About

This library contains extension methods for Object.

Install

npm i @locustjs/extensions-object

Usage

CommonJs

var someFn = require('@locustjs/extensions-object').someFn;

ES6

import { someFn } from '@locustjs/extensions-object'

function methods

isSubClassOf(parentClass)

Checks whether a Class is a sub-class of parentClass or not and returns true | false.

Example:

class Foo { }
class Bar extends Foo { }
class Buz { }

Bar.isSubClassOf(Foo);  // true
Buz.isSubClassOf(Foo);  // false

toJson(obj, replacer, space, filter)

Serializes obj into json format using JSON.stringify function.

Example 1:

const x = { name: 'John Doe', age: 23 };

// call directly
console.log(toJson(x));  // { "name": "John Doe", "age": 23 }

// as an extension method
console.log(x.toJson());  // { "name": "John Doe", "age": 23 }

It also supports cleaning the object before serialization (the cleaning is not applied to source object).

Example 2:

const x = { name: 'John Doe', address: null, scores:[], zip: "", age: 0, parent: {} };

console.log(toJson(x, "all"));
// { "name": "John Doe" }
// all props with null, undefined, 0, empty array, empty object values are filtered or ignored

merge(obj, obj1, obj2, ...)

Performs a deep merge on obj by given objects.

Example:

const x = { name: 'John' };
const a = { a: 10 }
const b = { b: 'test' }

// call directly
console.log(merge(x, a, b));  // { name: 'John', a: 10, b: 'test' }

// as an extension method
console.log(x.merge(a, b));  // { name: 'John', a: 10, b: 'test' }

flatten(obj, separator)

Flattens obj properties and returns an object whose properties has only primitive values. The default separator in separating property names is dot character.

Example:

const x = {
    name: 'John',
    address: {
        city: { id: 10, name: 'Tehran' },
        zip: '12345678'
    }
};

// call directly
console.log(flatten(x));
/*
{
    'name': 'John',
    'address.city.id': 10,
    'address.city.name': 'Tehran',
    'address.zip': '12345678',
}
*/

// as an extension method
console.log(x.flatten());

unflatten(obj, separator)

Unflattens a flattened obj. See flatten method.

Example:

const x = {
    name: 'John',
    address: {
        city: { id: 10, name: 'Tehran' },
        zip: '12345678'
    }
};

let y, z;
// call directly
y = flatten(x);
z = unflatten(y);

// as an extension method
y = x.flatten();
z = y.unflatten();

console.log(y1);
console.log(y2);
/*
{
    name: 'John',
    address: {
        city: { id: 10, name: 'Tehran' },
        zip: '12345678'
    }
}
*/

query(obj, path)

Queries obj based on given path.

Example:

const x = {
    name: 'John',
    address: {
        city: { id: 10, name: 'Tehran' },
        zip: '12345678'
    }
};

console.log(query(x, 'name'));	// John
console.log(query(x, 'address.city'));	//	{ id: 10, name: 'Tehran' }
console.log(query(x, 'address.city.id'));	// 10
console.log(query(x, 'address.city.name.length'));	// 6
console.log(query(x, 'address.city.state.code'));	// undefined
console.log(query(x, 'address.city.code'));	// undefined
console.log(query(x, 'age'));	// undefined

toArray(obj, type)

Converts an object to an array. The result depends on type. Possible values are as follows:

  • key-value or key/value or keyvalue: returns an array of key/value items where each key/value is an array with 2 items, the first item is key, the second is value.
  • values: retuns only values of properties as an array.
  • keys or schema: returns only property names as an array.

toArray is similar to Object.entries(). It performs a recursive/nested invokation on object property values whereas Object.entries() only acts on the first-level of properties.

Example:

const x = {
    name: 'John',
    address: {
        city: { id: 10, name: 'Tehran' },
        zip: '12345678'
    },
    age: 23
};

// ==== type: key-value =====
// call directly
console.log(toArray(x, `key-value`));

// as an extension method
console.log(x.toArray('key-value'));
/*
[
	["name", "John"],
	[
		"address",
		[
			[
				"city",
				[
					["id", 10],
					["name", "Tehran"]
				]
			],
			["zip", "12345678"]
		]
	],
	["age", 23]
]
*/

// ==== type: values =====
// call directly
console.log(toArray(x, `values`));

// as an extension method
console.log(x.toArray('values'));
/*
[
	"ali",
	[
		[10, "Tehran"],
		"123456789"
	],
	23
]
*/

// ==== type: keys =====
// call directly
console.log(toArray(x, 'keys'));

// as an extension method
console.log(x.toArray('keys'));
/*
[
	"name",
	[
		"address",
		[
			[
				"city",
				[
					"id",
					"name"
				]
			],
			"zip"
		]
	],
	"age"
]
*/

toArray function is best used in sending array of objects in the form of array of arrays and minimizing the length of json serialization result. It does this by factorizing prop names, producing a result whose size 30% less.

const data = [
	{ id: 1, name: "John", age: 34 },
	{ id: 2, name: "Jade", age: 33 },
	{ id: 3, name: "Joe", age: 28 },
	{ id: 4, name: "Jane", age: 31 },
	{ id: 5, name: "Jake", age: 29 },
]

const schema = toArray(data[0], "schema");
const items = data.map(x => toArray(x, "values"));
const newData = { schema, items }

const json1 = JSON.stringify(data);
const json2 = JSON.stringify(newData);

console.log(`Serialization size:`)
console.log(`	Normal way: ${json1.length}`)
console.log(`	toArray(): ${json2.length}`)
console.log(`	Improvement: ${Math.round((json1.length - json2.length) / json1.length * 100, 2)}%`)

/* Output:
Serialization size:
	Normal way: 160
	toArray(): 109
	Improvement: 32%
*/

toArray carries out reverse of a method named toObject() that is an extension method defined in @locustjs/extensions-array.

We can utilize toObject to restore back all objects from array format.

// Sender:
const data = [
	{ id: 1, name: "John", age: 34 },
	{ id: 2, name: "Jade", age: 33 },
	{ id: 3, name: "Joe", age: 28 },
	{ id: 4, name: "Jane", age: 31 },
	{ id: 5, name: "Jake", age: 29 },
]

const schema = toArray(data[0], "schema");
const items = data.map(x => toArray(x, "values"));
const newData = { schema, items }

// we now send newData over network to another party

// Receiver:
// the other party can restore back all objects.
const restoredData = newData.items.map(x => toObject(x, 'values', newData.schema))

// to testify that restoredData is the same shape as the original 'data',
// we can serialize them to json. they will both produce the same json.

const json1 = JSON.stringify(data);
const json2 = JSON.stringify(restoredData);

console.log(json1 == json2);	// true