Simple email application for Android. Original source code: https://framagit.org/dystopia-project/simple-email
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

111 lines
2.1 KiB

  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. }