blimpy
v0.0.6
Published
Easily set the class of an object.
Readme
Why?
Most databases don't store an object's prototype. This means if you're doing something like
firebaseRef.set(someFoodObject);
and then retrieving it later, it won't have the methods from FoodClass.
What should you do?
- Using
Object.setPrototypeOfis terrible for performance. - A combination of
Object.assignandObject.createis ugly if you're doing it over and over again. Object.createandObject.getOwnPropertyDescriptorsis even worse.
Using blimpy makes it easy to add a prototype to an object.
- blimpy is small (
blimpy.min.jsis less than400 bytes). - blimpy is simple (blimpy only uses
2built-in JS functions). - blimpy is well-tested (blimpy has
16tests using MochaJS)
Sample Usage
Get some object. It doesn't matter where from.
…from a database…
let foodObject = getFoodObjectFromDatabase('apple');…or with an object literal…
let foodObject = { name: 'apple', price: 5 };
Use blimpy.
let food = blimpy.withClass(FoodClass, foodObject);Profit. (Use the class's methods.)
food.eat(); console.log(food.getPriceStr());
Install
npm install --save blimpyFull Docs
withClass
Adds a class's prototype to an object (without mutating it).
blimpy.withClass(someClass, someObject)
someClass: The class to add.someObject: The object to add it to.- Returns: The new object with the class's prototype.
withProto
Adds a prototype to an object (without mutating it).
blimpy.withProto(someProto, someObject)
someClass: The prototype to add.someObject: The object to add it to.- Returns: The new object with the prototype.
withNoClass
Removes an object's prototype (without mutating it). Actually, this sets the object's prototype to Object.prototype (the default object prototype).
blimpy.withNoClass(someObject)
someObject: The object to remove the class from.- Returns: The new object without a prototype.
withNoProto
Removes an object's prototype (without mutating it). Unlike withNoClass, this sets the prototype of the object to null, not Object.prototype. For example, this means that blimpy.withNoClass(someObject).toString() works but blimpy.withNoProto(someObject).toString() does not.
blimpy.withNoClass(someObject)
someObject: The object to remove the class from.- Returns: The new object without a prototype.
Full Example File
// Require blimpy.
let blimpy = require('blimpy');
// Some arbitrary class.
class FoodClass {
constructor(name) {
this.name = name;
this.price = name.length;
}
getPriceStr() {
return '$' + this.price.toString();
}
}
// Some food object without the `FoodClass` prototype, in this case
// an object literal.
let foodObject = {
name: 'apple',
price: 5,
}
// Add the prototype with blimpy.
let food = blimpy.withClass(FoodClass, foodObject);
// Logs `$5`.
console.log(food.getPriceStr());