Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

index.js 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. 'use strict';
  2. var isObj = require('is-obj');
  3. module.exports.get = function (obj, path) {
  4. if (!isObj(obj) || typeof path !== 'string') {
  5. return obj;
  6. }
  7. var pathArr = getPathSegments(path);
  8. for (var i = 0; i < pathArr.length; i++) {
  9. var descriptor = Object.getOwnPropertyDescriptor(obj, pathArr[i]) || Object.getOwnPropertyDescriptor(Object.prototype, pathArr[i]);
  10. if (descriptor && !descriptor.enumerable) {
  11. return;
  12. }
  13. obj = obj[pathArr[i]];
  14. if (obj === undefined || obj === null) {
  15. // `obj` is either `undefined` or `null` so we want to stop the loop, and
  16. // if this is not the last bit of the path, and
  17. // if it did't return `undefined`
  18. // it would return `null` if `obj` is `null`
  19. // but we want `get({foo: null}, 'foo.bar')` to equal `undefined` not `null`
  20. if (i !== pathArr.length - 1) {
  21. return undefined;
  22. }
  23. break;
  24. }
  25. }
  26. return obj;
  27. };
  28. module.exports.set = function (obj, path, value) {
  29. if (!isObj(obj) || typeof path !== 'string') {
  30. return;
  31. }
  32. var pathArr = getPathSegments(path);
  33. for (var i = 0; i < pathArr.length; i++) {
  34. var p = pathArr[i];
  35. if (!isObj(obj[p])) {
  36. obj[p] = {};
  37. }
  38. if (i === pathArr.length - 1) {
  39. obj[p] = value;
  40. }
  41. obj = obj[p];
  42. }
  43. };
  44. module.exports.delete = function (obj, path) {
  45. if (!isObj(obj) || typeof path !== 'string') {
  46. return;
  47. }
  48. var pathArr = getPathSegments(path);
  49. for (var i = 0; i < pathArr.length; i++) {
  50. var p = pathArr[i];
  51. if (i === pathArr.length - 1) {
  52. delete obj[p];
  53. return;
  54. }
  55. obj = obj[p];
  56. }
  57. };
  58. module.exports.has = function (obj, path) {
  59. if (!isObj(obj) || typeof path !== 'string') {
  60. return false;
  61. }
  62. var pathArr = getPathSegments(path);
  63. for (var i = 0; i < pathArr.length; i++) {
  64. obj = obj[pathArr[i]];
  65. if (obj === undefined) {
  66. return false;
  67. }
  68. }
  69. return true;
  70. };
  71. function getPathSegments(path) {
  72. var pathArr = path.split('.');
  73. var parts = [];
  74. for (var i = 0; i < pathArr.length; i++) {
  75. var p = pathArr[i];
  76. while (p[p.length - 1] === '\\' && pathArr[i + 1] !== undefined) {
  77. p = p.slice(0, -1) + '.';
  78. p += pathArr[++i];
  79. }
  80. parts.push(p);
  81. }
  82. return parts;
  83. }