@creanet/records-set
v1.0.2
Published
Set of records with one or more unique properties
Downloads
3
Readme
Records Set
Class for storing a set of records with unique property.
Installation
To install this module use npm or yarn:
npm install @creanet/records-set
yarn add @creanet/records-set
After the module is installed, require it anywhere in the code:
const RecordsSet = require('@creanet/records-set');
Creating new instance
To create a new instance of Records Set, constructor should be called with two parameters:
const RecordsSet = require('@creanet/records-set');
const uniqueProp = 'id';
const iterable = [
{
id: '1',
foo: 'obj1'
},
{
id: '2',
foo: 'obj2'
},
{
id: '2',
foo: 'obj3'
}
];
const set = new RecordsSet(uniqueProp, iterable);
console.log(set.values()); // [ { id: '1', foo: 'obj1' }, { id: '2', foo: 'obj2' } ]
Properties
size
Returns the number of the records in RecordsSet:
console.log(set.size); // 2
console.log(set.size === set.values().length); // true
Methods
values()
Returns an array with all records (values):
console.log(set.values()); // [ { id: '1', foo: 'obj1' }, { id: '2', foo: 'obj2' } ]
has(record)
Determines whether set contains such record by looking for unique property. All other properties will be ignored:
console.log(set.has({ id: '2', foo: 'obj2' })); // true
console.log(set.has({ id: '2', foo: 'obj3' })); // true
console.log(set.has({ id: '3', foo: 'obj4' })); // false
add(values)
Used to add one or more records. Records with already registered unique prop will be ignored:
set.add({ id: '2', foo: 'obj5' });
console.log(set.size); // 2
set.add({ id: '3', foo: 'obj6' });
console.log(set.size); // 3
delete(values)
Used to delete one or more records. Delete can either be passed a record with the unique property:
set.delete({ id: '2', foo: 'obj7' });
console.log(set.values()); // [ { id: '1', foo: 'obj1' }, { id: '3', foo: 'obj6' } ]
Or a simple value:
set.delete('1');
console.log(set.values()); // [ { id: '3', foo: 'obj6' } ]
clear()
Removes all records:
set.clear();
console.log(set.values()); // []
Iteration methods
Records set can be iterated using these methods:
set.forEach(callback, thisArg);
set.map(callback, thisArg);
set.filter(callback, thisArg);
Methods map and filter return a new instance of RecordsSet, forEach returns the original RecordsSet. Alternatively it is possible to use any array iteration method by calling it on the values of the set:
set.values()[iterationMethod];
Some array iteration methods return an array. To turn the result into set, simply call:
set = new Set(set.uniqueProp, set.values().map(callback));