UNPKG

1.58 kBJavaScriptView Raw
1/**
2 * @copyright Copyright (c) 2019 Maxim Khorin <maksimovichu@gmail.com>
3 */
4'use strict';
5
6module.exports = class NestedValueHelper {
7
8 static get (key, data, defaults) { // key: 'prop1.prop2.prop3'
9 if (!data || typeof key !== 'string') {
10 return defaults;
11 }
12 if (Object.prototype.hasOwnProperty.call(data, key)) {
13 return data[key];
14 }
15 const index = key.indexOf('.');
16 if (index < 1) {
17 return defaults;
18 }
19 const token = key.substring(0, index);
20 if (!Object.prototype.hasOwnProperty.call(data, token)) {
21 return defaults;
22 }
23 key = key.substring(index + 1);
24 data = data[token];
25 if (Array.isArray(data)) {
26 return data.map(item => this.get(key, item, defaults));
27 }
28 return data ? this.get(key, data, defaults) : defaults;
29 }
30
31 static set (value, key, data) { // key: 'prop1.prop2.prop3'
32 const index = key.indexOf('.');
33 if (index === -1) {
34 return data[key] = value;
35 }
36 const token = key.substring(0, index);
37 if (!(data[token] instanceof Object)) {
38 data[token] = {};
39 }
40 this.set(value, key.substring(index + 1), data[token]);
41 }
42
43 static includes () {
44 return this.indexOf(...arguments) !== -1;
45 }
46
47 static indexOf (value, key, data) {
48 const values = this.get(key, data);
49 return Array.isArray(values) ? values.indexOf(value) : -1;
50 }
51};
\No newline at end of file