forked from RafaelVidaurre/yakuza
-
Notifications
You must be signed in to change notification settings - Fork 0
/
options.js
94 lines (75 loc) · 2.14 KB
/
options.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/**
* Utility for building Http module options with ease
* @module Options
* @author Rafael Vidaurre
*/
'use strict';
var _;
_ = require('lodash');
/**
* @class
* @param {object} defaultOptions POJO with default options
*/
function Options (defaultOptions) {
if (defaultOptions && !_.isObject(defaultOptions)) {
throw new Error('Default options must be an object');
}
this._defaults = defaultOptions || {};
this._currentOptions = this._defaults;
}
/**
* Set default options to be used, if no argument is passed returns it instead
* @param {object} defaultOptions default options to be used
* @return current default options if argument is set, otherwise undefined
* @public
*/
Options.prototype.defaults = function (defaultOptions) {
if (!defaultOptions) {
return _.cloneDeep(this._defaults);
}
if (!_.isObject(defaultOptions)) {
throw new Error('Default options must be an object');
}
this._defaults = defaultOptions;
};
/**
* Extends the current options object with the options provided
* @param {object} options Options object to be used for extension
* @return {object} currentOptions current set options
*/
Options.prototype.extend = function (options) {
if (!_.isObject(options)) {
throw new Error('Options must be an object');
}
this._currentOptions = _.extend(this._currentOptions, options);
return this.options();
};
/**
* Returns a clone of the current options set, or extends current set options if object is provided
* @return {object} clone of current options
*/
Options.prototype.options = function (options) {
if (_.isObject(options)) {
this.extend(options);
}
return _.cloneDeep(this._currentOptions);
};
/**
* Sets a new value for a given key
* @param {string} key Key to which the value is assigned
* @param value Value asigned to the key
*/
Options.prototype.set = function (key, value) {
this._currentOptions[key] = value;
return this.options();
};
/**
* Resets options instance to defaults
* @public
*/
Options.prototype.reset = function () {
this._currentOptions = this._defaults;
};
/** @alias defaults */
Options.prototype.default = Options.prototype.defaults;
module.exports = Options;