A set of DRY methods to work with flat key
const entity = {
folder: "./app",
file: "securityEntities.type.ts",
typeName: "User",
fields: [{
name: "userId",
...
}]
};const entityFlatKey = {
folder: entity.folder,
file: entity.file,
typeName: entity.typeName
};
`
I could also recommend defining such a complex key from the beginning, then entity would look like this:
`
const entity = {
id: {
folder: "./app",
file: "securityEntities.type.ts",
typeName: "User",
},
fields: [{
name: "userId",
...
}]
};
`
This way you don't need to construct new object each time you have to use that key.
Second limitation to the flat key is that all entities of the same type should have the same structure of the key, i.e. no fields can be omitted. This is needed for methods of this library to work properly. Type of key (primitive or flat) and a number of key fields is determined upon encountering first key of the collection.groupBy
This method groups object by a key, works with both primitive keys or flat object. Returns a KeyGroup object.
`
import { groupBy } from "@b08/flat-key";
const entities = []; // populated somewhere
const grouped = groupBy(entities, e => e.id);
const key = entities[3].id;
const entities3 = grouped.get(key); // all entities that have same flat-key id as entities[3]
`
KeyGroup has following methods:
1. keys() and values() - self explanatory.
2. add(key, item) - adds item against the key.
3. addItem(item) - gets a key using selector then adds it.
4. get(key) - return array of items by the key, null if key is not present.
5. has(key) - returns true if key is present.
6. hasItem(item) - return true if specific item is present. O(n) and reference equality.
7. delete(key) - deletes all items by the key.
8. deleteItem(item) - deletes specific item and returns true if item was present and successfully deleted. O(n) and reference equality.Can call KeyGroup constructor directly instead of groupBy.
mapBy
Works similar to groupBy, except the key is assigned to only one value. It the same key encountered for the second time, it is overwritten.
Returns KeyMap object. KeyMap has following methods:
1. keys() and values() - self explanatory.
2. add(key, item) - adds item against the key.
3. addItem(item) - gets a key using selector then adds it.
4. get(key) - return item by the key, null if key is not present.
5. has(key) - returns true if key is present.
6. hasItem(item) - return true if specific item is in the store. Reference equality.
7. delete(key) - deletes item by the key.
8. deleteItem(item) - deletes item. Returns true if successfully deleted. Reference equality.Can call KeyMap constructor directly instead of groupBy.
unique
Returns entities unique by their keys. Key can also be both primitive and flat.
`
const entities = []; // populated somewhere
const filtered = unique(entities, e => e.id);
``