From 8040600326ff3a7cb5d11d16577c15a3e37388fd Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Tue, 12 Dec 2017 12:06:56 -0800 Subject: [PATCH] config: add filter method. --- lib/config.js | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/lib/config.js b/lib/config.js index e3da0be..0ac28fa 100644 --- a/lib/config.js +++ b/lib/config.js @@ -145,6 +145,31 @@ class Config { this.prefix = this.getPrefix(); } + /** + * Create a child config. Filter by plugin name. + * @param {String} name + * @returns {Config} + */ + + filter(name) { + assert(typeof name === 'string'); + + const child = new Config(this.module); + + child.prefix = this.prefix; + child.suffix = this.suffix; + child.fallback = this.fallback; + child.argv = this.argv; + child.pass = this.pass; + + _filter(name, this.env, child.env); + _filter(name, this.args, child.args); + _filter(name, this.query, child.query); + _filter(name, this.hash, child.hash); + + return child; + } + /** * Set default option. * @param {String} key @@ -1106,6 +1131,15 @@ function isUpperKey(key) { return !/[a-z]/.test(key); } +function _filter(name, a, b) { + for (const key of Object.keys(a)) { + if (key.length > name.length && key.indexOf(name) === 0) { + const sub = key.substring(name.length); + b[sub] = a[key]; + } + } +} + function fromFloat(num, exp) { assert(typeof num === 'number' && isFinite(num)); assert(Number.isSafeInteger(exp));