Skip to content
This repository has been archived by the owner on Dec 10, 2019. It is now read-only.

joeattardi/track-property

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

About

Track the history of property sets/gets in JavaScript objects

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published