Defo
A method_missing(or Hash.new) lib for JavaScript.
Defo pronounce 'default' without /t$/.
Installation
npm install defo
Quick Examples
Set default value with a literal JS Object
var Defo = ;var defo = '@@@';console; // => '@@@'console; // => '@@@'
More advanced, with a Function
var Defo = ; var defo = { return key + '!!!';}; console; // => Hello!!!
To see more(and more advanced) examples, please visit:
Documentation
- #initialize
- #set
- #get
- #toObject
#initialize
Defo can be initialized when create a new Defo instance
With literal object:
var defo = a: 1 b: 2;var defo2 = 1 2 3;
With a function:
var defo = { var value = ...// dosomething with key return value;};
#set && get
var defo = ;defo;defoheight = 180;console; // => { name: 'Alsotang', age: 21, height: 1.8 }console; // => undefined
chaining set
var defo = ; defo ;defoheight = 180;console;// output:// { person: { name: 'Alsotang', age: 21, height: 1.8 },// pet: { name: 'Piglet', age: 3 } }
set with a Hash
var defo = ;defo;defoshould; // => truedefoshould; // => true
#toObject
toObject would convert your Defo to a JavaScript Object.
This method will create a new object instead of modify Defo object.
var person = ;person ; var pet = ;pet ; var house = ;house ; console;// output:// { person: { name: 'Alsotang', age: 21 },// pet: { name: 'Piglet', age: 3 } }
Memoize
var fibonacci = { if key === 1 || key === 2 this; return this; this; return this;};fibonaccishould; // 610 is 15-th of fibonacci sequencefibonaccishould;fibonacci_backedshould;
Why I create Defo
In my work, there are lots of situations to deal with data structure transformation.
For example, there is some rows from SQL database:
var ROWS = // Name, Height, Weight, Country "Alsotang" 180 60 "Chinese" "YB" 165 50 "Chinese" "Jack" 179 70 "American" "Lucy" 170 100 "American";
and I need to transform it to below:
var RESULTS = "Chinese": "Alsotang": "Height": 180 "Weight": 60 "YB": "Height": 165 "Weight": 50 "American": "Jack": "Height": 179 "Weight": 70 "Lucy": "Height": 170 "Weight": 100 ;
With Defo, I can just write:
var result = // in this Defo, key would be Chinese or American // would be Alsotang or Jack in this // Height or Weight ;ROWS;resultshould; // => true
And it works! Otherwise the implement code is ugly, especially when the data structure is not such simple.