OptionsDefaulter.js 1.8 KB

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