OptionsDefaulter.js 1.9 KB

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