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.

63 lines
1.6 KiB

  1. /*
  2. * grunt
  3. * http://gruntjs.com/
  4. *
  5. * Copyright (c) 2013 "Cowboy" Ben Alman
  6. * Licensed under the MIT license.
  7. * https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
  8. */
  9. (function(exports) {
  10. 'use strict';
  11. // Split strings on dot, but only if dot isn't preceded by a backslash. Since
  12. // JavaScript doesn't support lookbehinds, use a placeholder for "\.", split
  13. // on dot, then replace the placeholder character with a dot.
  14. function getParts(str) {
  15. return str.replace(/\\\./g, '\uffff').split('.').map(function(s) {
  16. return s.replace(/\uffff/g, '.');
  17. });
  18. }
  19. // Get the value of a deeply-nested property exist in an object.
  20. exports.get = function(obj, parts, create) {
  21. if (typeof parts === 'string') {
  22. parts = getParts(parts);
  23. }
  24. var part;
  25. while (typeof obj === 'object' && obj && parts.length) {
  26. part = parts.shift();
  27. if (!(part in obj) && create) {
  28. obj[part] = {};
  29. }
  30. obj = obj[part];
  31. }
  32. return obj;
  33. };
  34. // Set a deeply-nested property in an object, creating intermediary objects
  35. // as we go.
  36. exports.set = function(obj, parts, value) {
  37. parts = getParts(parts);
  38. var prop = parts.pop();
  39. obj = exports.get(obj, parts, true);
  40. if (obj && typeof obj === 'object') {
  41. return (obj[prop] = value);
  42. }
  43. };
  44. // Does a deeply-nested property exist in an object?
  45. exports.exists = function(obj, parts) {
  46. parts = getParts(parts);
  47. var prop = parts.pop();
  48. obj = exports.get(obj, parts);
  49. return typeof obj === 'object' && obj && prop in obj;
  50. };
  51. }(typeof exports === 'object' && exports || this));