From d61b2ebeb849942f9268208062739f78234751ab Mon Sep 17 00:00:00 2001 From: Marat Dreizin Date: Fri, 10 Jun 2016 03:07:11 +0300 Subject: [PATCH] feat(Config): adds some new methods: `set`, `get`, `remove`, `has` --- src/Config.js | 49 +++++++++++++++++++++++++++++++++++++++++++-- test/Config.spec.js | 48 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+), 2 deletions(-) diff --git a/src/Config.js b/src/Config.js index 221d2ff..c7d9fc5 100644 --- a/src/Config.js +++ b/src/Config.js @@ -2,7 +2,11 @@ import { isFunction, isObject, defaultsDeep, - mergeWith + mergeWith, + set, + unset, + get, + has } from 'lodash'; import ConfigLoader from './ConfigLoader'; import ConfigTransform from './ConfigTransform'; @@ -228,7 +232,7 @@ class Config { const properties = {}; for (const [key, value] of Object.entries(this)) { - if (this.hasOwnProperty(key)) { + if (this.has(key)) { properties[key] = value; } } @@ -238,6 +242,47 @@ class Config { return properties; } + /** + * Sets `value` at `path` + * @param {String} path + * @param {*} value + * @return {Config} + */ + set(path, value) { + set(this, path, value); + + return this; + } + + /** + * Gets `value` at `path` + * @param {String} path + * @return {*} + */ + get(path) { + return get(this, path); + } + + /** + * Removes `value` at `path` + * @param {String} path + * @return {Config} + */ + remove(path) { + unset(this, path); + + return this; + } + + /** + * Checks if `value` exist at `path` + * @param {String} path + * @return {Boolean} + */ + has(path) { + return has(this, path); + } + /** * Initializes new {@link Config} with specific `values` * @param {...Object} values diff --git a/test/Config.spec.js b/test/Config.spec.js index 984f5cc..0cfefa2 100644 --- a/test/Config.spec.js +++ b/test/Config.spec.js @@ -195,6 +195,54 @@ describe('Config', () => { }); }); + describe('#set()', () => { + it('should add `value` at `path`', () => { + config.set('foo', { + bar: 'bar1' + }); + + expect(config.toObject()).toEqual({ + foo: { + bar: 'bar1' + } + }); + }); + }); + + describe('#remove()', () => { + it('should remove `value` at `path`', () => { + config.merge({ + foo: 'foo1' + }).remove('foo'); + + expect(config.toObject()).toEqual({}); + }); + }); + + describe('#get()', () => { + it('should get `value` at `path`', () => { + config.merge({ + foo: 'foo1' + }); + + expect(config.get('foo')).toEqual('foo1'); + }); + }); + + describe('#has()', () => { + it('should return `true` if `path` exist', () => { + config.merge({ + foo: 'foo1' + }); + + expect(config.has('foo')).toEqual(true); + }); + + it('should return `false` if `path` absent', () => { + expect(config.has('foo')).toEqual(false); + }); + }); + describe('.initWith()', () => { it('should return `Config`', () => { config = Config.initWith({