Skip to content

davidecalignano/byid

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

42 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

byId Build Status Coverage Status

Makes array of objects accessible

Motivation

ById is inspired by the normalized way to handle the state in redux and the normalizr utility.

Unlike normalizr, byId does not group the data in entities and you don't create relationship data on entities to preserve the information on nested objects, but rather it maintains the object structure as the input and normalizes all the arrays recursivly based on a schema which specify what should be normalized and what not.

Advantages

  • The normalization makes easy to access to array of items withouth iterating over it.
  • Improves performances.

Install

npm install byid

API

normalize(data, schema)

Return the normalized data based on the provided schema.

  • data: required Data that needs normalization.
  • schema: required An object that defines the schema of what needs normalizations and additionally specify the key (default id). All the data not specified in the schema will be copied in the new object as is.

Usage

import { normalize } from 'byid';
const data = {
    name: 'Mark',
    posts: [{id: 123, comments: []}, {id: 456, comments: []}]
}
const schema = {
    posts: {}
}

const output = normalize(data, schema)

Output

{
    name: 'Mark',
    posts: {
        ids: [123, 456],
        byId: {
            123: {id: 123, comments: []},
            456: {id: 456, comments: []}
        }
    }
}

denormalize(data, schema)

Return the original data based on the provided schema.

  • data: required Data that needs to be reverted in the original shape.
  • schema: required The schema provided in the normalization.

Usage

import { denormalize } from 'byid';
const data = {
    name: 'Mark',
    posts: {
        ids: [123, 456],
        byId: {
            123: {id: 123, comments: []},
            456: {id: 456, comments: []}
        }
    }
}
const schema = {
    posts: {}
}

const output = denormalize(data, schema)

Output

{
    name: 'Mark',
    posts: [{id: 123, comments: []}, {id: 456, comments: []}]
}

Examples

Nested normalization

Dependencies

None.