File: index.js

package info (click to toggle)
node-object-key 0.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 92 kB
  • sloc: makefile: 10; sh: 2
file content (75 lines) | stat: -rw-r--r-- 1,638 bytes parent folder | download | duplicates (2)
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
'use strict';

if (typeof module === 'object' && module.exports) {
  var _ = require('lodash');
}

!function() {
  var ok = { version: '0.1.0' };

  /**
   * Assign value to object property.
   *
   * @param {string} key
   * @param {(string|number|object|array)} value
   * @param {object} hash
   * @param {string} stringCase
   *
   * @return {object}
   */
  ok.assign = function assign(object, path, value, stringCase) {
    var convertCase;

    switch(stringCase) {
      case 'camel':
        convertCase = _.camelCase;
        break;
      case 'kebab':
        convertCase = _.kebabCase;
        break;
      case 'snake':
        convertCase = _.snakeCase;
        break;
      default:
        convertCase = function convertCase(d) { return d; };
        break;
    }

    let keys = path.split('.');
    keys = _.map(keys, convertCase);
    keys = keys.join('.');
  
    return _.set(object, keys, value);
  }

  /**
   * Lookup key value
   *
   * @param {string} key
   * @param {object} hash
   *
   * @return {(string|number|object|array)}
   */
  ok.lookup = function lookup(key, hash) {
      let firstKey;
      let idx;
      let remainingKeys;
  
    if (hash[key] !== undefined) { return hash[key]; }
  
    if ((idx = key.indexOf('.')) !== -1) {
      firstKey = key.substr(0, idx);
      remainingKeys = key.substr(idx + 1);
      hash = hash[firstKey];
      if (hash) { return lookup(remainingKeys, hash); }
    }
  }

  if (typeof define === 'function' && define.amd) {
    define(ok);
  } else if (typeof module === 'object' && module.exports) {
    module.exports = ok;
  } else {
    this.ok = ok;
  }
}();