UNPKG

2.2 kBJavaScriptView Raw
1
2/**
3 A simple dictionary of Variable() objects
4
5 note: you may inject your own variables when calling the constructor
6**/
7
8var check = require('check-types'),
9 Variable = require('./Variable');
10
11function VariableStore( vars ){
12 this._vars = {};
13 if( check.assigned( vars ) ){
14 this.set( vars );
15 }
16}
17
18/**
19 var() can be used as *both* a getter *or* a setter (as per jquery)
20 depending on how many arguments are set.
21
22 var vs = new VariableStore();
23
24 // to get a variable:
25 var a = vs.var('foo');
26
27 // to set a variable:
28 vs.var('foo','bar');
29
30 // or
31 vs.var('foo').set('bar');
32**/
33VariableStore.prototype.var = function( key, val ){
34 if( !check.nonEmptyString( key ) ){
35 throw new Error( 'invalid query variable, key must be valid string' );
36 }
37 // init variable
38 if( !this._vars.hasOwnProperty( key ) ){
39 this._vars[ key ] = new Variable();
40 }
41 // setter
42 if( check.assigned( val ) ){
43 this._vars[ key ].set( val );
44 }
45 // getter
46 return this._vars[ key ];
47};
48
49/**
50 check if a key has been set (has a value)
51**/
52VariableStore.prototype.isset = function( key ){
53 if( !check.nonEmptyString( key ) ){
54 throw new Error( 'invalid key, must be valid string' );
55 }
56 // key not set
57 if( !this._vars.hasOwnProperty( key ) ){
58 return false;
59 }
60 // true if value is set else false
61 return this._vars[ key ].get() !== '';
62};
63
64/**
65 delete a variable by key
66**/
67VariableStore.prototype.unset = function( key ){
68 if( !check.nonEmptyString( key ) ){
69 throw new Error( 'invalid key, must be valid string' );
70 }
71 // key not set
72 if( !this._vars.hasOwnProperty( key ) ){
73 return false;
74 }
75 // delete variable
76 delete this._vars[ key ];
77 return true;
78};
79
80/**
81 import variables from a plain-old-javascript-object
82**/
83VariableStore.prototype.set = function( pojo ){
84 if( !check.object( pojo ) ){
85 throw new Error( 'invalid object' );
86 }
87 for( var attr in pojo ){
88 this.var( attr ).set( pojo[attr] );
89 }
90};
91
92/**
93 export variables for debugging purposes
94**/
95VariableStore.prototype.export = function(){
96 var out = {};
97 for( var v in this._vars ){
98 out[ v ] = this._vars[v].get();
99 }
100 return out;
101};
102
103module.exports = VariableStore;