OptionsDefaulter.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. function OptionsDefaulter() {
  6. this.defaults = {};
  7. this.config = {};
  8. }
  9. module.exports = OptionsDefaulter;
  10. function getProperty(obj, name) {
  11. name = name.split(".");
  12. for(var i = 0; i < name.length - 1; i++) {
  13. obj = obj[name[i]];
  14. if(typeof obj != "object" || !obj) return;
  15. }
  16. return obj[name.pop()];
  17. }
  18. function setProperty(obj, name, value) {
  19. name = name.split(".");
  20. for(var i = 0; i < name.length - 1; i++) {
  21. if(typeof (obj[name[i]]) !== "object" || !obj[name[i]]) obj[name[i]] = {};
  22. obj = obj[name[i]];
  23. }
  24. obj[name.pop()] = value;
  25. }
  26. function hasProperty(obj, name, value) {
  27. name = name.split(".");
  28. for(var i = 0; i < name.length - 1; i++) {
  29. obj = obj[name[i]];
  30. if(typeof obj != "object" || !obj) return false;
  31. }
  32. return Object.prototype.hasOwnProperty.call(obj, name.pop());
  33. }
  34. OptionsDefaulter.prototype.process = function(options) {
  35. for(var name in this.defaults) {
  36. switch(this.config[name]) {
  37. case undefined:
  38. if(getProperty(options, name) === undefined)
  39. setProperty(options, name, this.defaults[name]);
  40. break;
  41. case "call":
  42. setProperty(options, name, this.defaults[name].call(this, getProperty(options, name)), options);
  43. break;
  44. case "append":
  45. var oldValue = getProperty(options, name);
  46. if(!Array.isArray(oldValue)) oldValue = [];
  47. this.defaults[name].forEach(function(item) {
  48. oldValue.push(item);
  49. });
  50. setProperty(options, name, oldValue);
  51. break;
  52. default:
  53. throw new Error("OptionsDefaulter cannot process " + this.config[name]);
  54. }
  55. }
  56. };
  57. OptionsDefaulter.prototype.set = function(name, config, def) {
  58. if(arguments.length === 3) {
  59. this.defaults[name] = def;
  60. this.config[name] = config;
  61. } else {
  62. this.defaults[name] = config;
  63. delete this.config[name];
  64. }
  65. }