jsprim: JavaScript Primitive Utilities

2.0.2 · maintenance · verified Sun Apr 19

jsprim is a utility library focused on fundamental operations for JavaScript primitive types and common object manipulations. It provides functions for deep cloning, thorough deep equality comparisons, and efficient inspection/transformation of object structures, including an O(1) `isEmpty` check and memory-efficient `flattenIter` for traversing deeply nested objects without materializing the full result array. The current stable version is 2.0.2, with the last update approximately four years ago. It targets older Node.js environments (originally requiring Node.js >=0.6.0) and uses the CommonJS module system, making it suitable for legacy projects or environments where explicit CJS interop is managed.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates core utilities like deepCopy, deepEqual, isEmpty, pluck for nested property access, and flattenIter for efficient object traversal without materializing full arrays.

const jsprim = require('jsprim');

// Example 1: Deep Copy
const originalObject = { a: 1, b: { c: 2 }, d: [3, 4] };
const copiedObject = jsprim.deepCopy(originalObject);
console.log('Deep Copy:', copiedObject);
console.log('Are copies identical? (reference check):', originalObject === copiedObject); // Should be false
console.log('Are contents deeply equal:', jsprim.deepEqual(originalObject, copiedObject)); // Should be true

// Example 2: Deep Equal
const obj1 = { x: 1, y: { z: 2 } };
const obj2 = { x: 1, y: { z: 2 } };
const obj3 = { x: 1, y: { z: 3 } };
console.log('Deep Equal (obj1, obj2):', jsprim.deepEqual(obj1, obj2)); // Should be true
console.log('Deep Equal (obj1, obj3):', jsprim.deepEqual(obj1, obj3)); // Should be false

// Example 3: Is Empty
console.log('Is {} empty?', jsprim.isEmpty({})); // Should be true
console.log('Is {a: 1} empty?', jsprim.isEmpty({ a: 1 })); // Should be false

// Example 4: Pluck
const nestedObject = {
    user: {
        profile: {
            name: 'Alice',
            age: 30
        },
        settings: { theme: 'dark' }
    },
    'user.id': '123'
};
console.log('Pluck user.profile.name:', jsprim.pluck(nestedObject, 'user.profile.name')); // Should be 'Alice'
console.log('Pluck user.id:', jsprim.pluck(nestedObject, 'user.id')); // Should be '123' (direct property takes precedence)
console.log('Pluck nonExistent.path:', jsprim.pluck(nestedObject, 'nonExistent.path')); // Should be undefined

// Example 5: flattenIter (demonstrates use without full array materialization)
const data = {
    'RegionA': { 'CityX': { 'pop': 100 }, 'CityY': { 'pop': 200 } },
    'RegionB': { 'CityZ': { 'pop': 300 } }
};
const flattenedResults = [];
jsprim.flattenIter(data, 2, (entry) => {
    flattenedResults.push(entry);
});
console.log('Flattened results (using flattenIter):', flattenedResults);

view raw JSON →