UNPKG

2.11 kBJavaScriptView Raw
1/**
2 * @copyright Copyright (c) 2019 Maxim Khorin <maksimovichu@gmail.com>
3 */
4'use strict';
5
6module.exports = class NestedHelper {
7
8 static get (key, data, defaults) {
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 getAlone (key, data, defaults) {
32 if (!data || typeof key !== 'string') {
33 return defaults;
34 }
35 if (Object.prototype.hasOwnProperty.call(data, key)) {
36 return data[key];
37 }
38 const index = key.indexOf('.');
39 if (index < 1) {
40 return defaults;
41 }
42 const token = key.substring(0, index);
43 return data[token] && Object.prototype.hasOwnProperty.call(data, token)
44 ? this.getAlone(key.substring(index + 1), data[token], defaults)
45 : defaults;
46 }
47
48 static set (value, key, data) {
49 const index = key.indexOf('.');
50 if (index === -1) {
51 return data[key] = value;
52 }
53 const token = key.substring(0, index);
54 if (!(data[token] instanceof Object)) {
55 data[token] = {};
56 }
57 this.set(value, key.substring(index + 1), data[token]);
58 }
59
60 static includes () {
61 return this.indexOf(...arguments) !== -1;
62 }
63
64 static indexOf (value, key, data) {
65 const values = this.get(key, data);
66 return Array.isArray(values) ? values.indexOf(value) : -1;
67 }
68};
\No newline at end of file