A simple library that handles a few records easily.
npm install js-memory-record
class Gender extends MemoryRecord {
static get define() {
return [
{ key: "male" },
{ key: "female" },
]
}
}
gender = Gender.fetch("male")
gender.name // => "male"
gender.code // => 0
Gender.fetch(0).name // => "male"
Return an array of Hash structures in define()
import MemoryRecord from 'js-memory-record'
export default class Fruit extends MemoryRecord {
// Record definition.
static get define() {
return [
{ key: "apple", name: "Poison Apple", price: 120, },
{ key: "melon", name: "Green Melon", price: 800, },
{ key: "peach", name: "Pink Piece", price: 200, },
]
}
// Define an instance method referencing an attribute.
// Define it when accessing other than key, name and other attributes
get full_name() {
return `${this.name} (Now ${this.special_price} Gold)`
}
get special_price() {
return Math.ceil(this.price / 2)
}
}
Basic access by this method.
Fruit.fetch("apple").key // => "apple"
Fruit.fetch("apple").name // => "Poison Apple"
Fruit.fetch("apple").code // => 0
Fruit.fetch("apple").index // => 0
Code is something like database ID. Allocate in order from 0. Use it when you want to access by special index.
Fruit.fetch(0).name // => "Poison Apple"
Fruit.fetch(0) === Fruit.fetch("apple") // => true
Fruit.fetch("apple").price // => 120
Define the Instance Metod freely and return the attributes in an easy-to-use form. This part is one of the merits of introducing this library.
Fruit.fetch("apple").special_price // => 60
Fruit.fetch("apple").full_name // => "Poison Apple (Now 60 Gold)"
There is no lookup()
exception.
Fruit.lookup("grape") // => null
In case of fetch()
we will throw an exception.
Fruit.fetch("grape") // (Throw Error)
The error message of the exception is displayed as follows.
Error: Fruit.fetch("grape") does not match anything
keys: ["apple","melon","peach"]
codes: [0,1,2]
The cause of the error is displayed in an easy-to-understand manner.
Fruit.values // => [{...}, {...}, {...}]
Fruit.values.map(e => e.key) // => ["apple", "melon", "peach"]
Fruit.keys // => ["apple", "melon", "peach"]
Fruit.codes // => [0, 1, 2]
Fruit.names // => ["Poison Apple", "Green Melon", "Pink Piece"],
We do not use this class methods much. But it may be useful for debugging.
static get define() {
return [
{ code: 1, key: "apple", },
{ code: 2, key: "melon", },
{ code: 4, key: "peach", },
]
}
Fruit.codes // => [1, 2, 4]
This is like managing database ID yourself. We do not recommend it. It is only useful if you need consistency with old data.
Replace the entire record internally held. I do not recommend this method much. But it may be useful in emergency.
Fruit.memory_record_reset([
{ key: "foo" },
{ key: "bar" },
])
Fruit.fetch("foo").key // => "foo"
# install dependencies
npm install
# build for production with minification
npm run build
# run unit tests
npm test
memory_record_reset