track-property

1.1.0 • Public • Published

track-property

track-property lets you keep a history of when a property on an object was set or accessed.

Installation

npm install --save track-property

Usage

The trackProperty function takes a JavaScript object, the name of the property, and an optional array of operation types to track. The supported operation types are set and get.

The function then returns an array. This array will be updated with entries whenever a property is set or accessed.

const trackProperty = require('track-property'):
 
const myObject = {};
const history = trackProperty(myObject, 'name');
 
myObject.name = 'Joe';
console.log(myObject.name);
 
console.log(history);

After running this code, history will contain two entries:

[
  {
    type: 'set',
    timestamp: Date, // this is a Date object that represents the timestamp of when the operation took place
    previousValue: undefined,
    newValue: 'Joe'
  },
  {
    type: 'get',
    timestamp: Date,
    value: 'Joe'
  }
]

If you only want to track only get or only set operations, pass the desired operation type in an array as the third argument:

const trackProperty = require('track-property');
 
const myObject = {};
const history = trackProperty(myObject, 'name', ['get']);
 
myObject.name = 'Joe';
console.log(myObject.name);

In the above example, the history array will contain just one entry:

[
  {
    type: 'get',
    timestamp: Date,
    value: 'Joe'
  }
]

Callback function

In addition to keeping a list of the set/get history, you can also define a callback function that will get called whenever there is a set or get operation:

const trackProperty = require('track-property');
 
const myObject = {};
trackProperty(myObject, 'name', ['set', 'get'], record => {
  console.log(`New ${record.type} operation on obj:`, record);
});

Dependencies (0)

    Dev Dependencies (6)

    Package Sidebar

    Install

    npm i track-property

    Weekly Downloads

    1

    Version

    1.1.0

    License

    MIT

    Unpacked Size

    7.29 kB

    Total Files

    8

    Last publish

    Collaborators

    • joeattardi