1. class HTMLValidator {
  2. constructor(rateLimit = { limit: 10, interval: 1000 }) {
  3. this.rateLimit = rateLimit;
  4. this.lastRun = 0;
  5. this.queue = [];
  6. }
  7. validateHTML(html, conditions) {
  8. const now = Date.now();
  9. if (now - this.lastRun > this.rateLimit.interval) {
  10. this.lastRun = now;
  11. } else {
  12. this.queue.push({ html, conditions });
  13. return; // Rate limited, don't validate
  14. }
  15. this.validateQueue();
  16. this.runValidation(html, conditions).then(result => {
  17. console.log("Validation Result:", result);
  18. }).catch(err => {
  19. console.error("Validation Error:", err);
  20. });
  21. }
  22. validateQueue() {
  23. while (this.queue.length > 0) {
  24. const item = this.queue.shift();
  25. this.runValidation(item.html, item.conditions);
  26. }
  27. }
  28. runValidation(html, conditions) {
  29. return new Promise((resolve, reject) => {
  30. try {
  31. const parser = new DOMParser();
  32. const doc = parser.parseFromString(html, 'text/html');
  33. let allConditionsMet = true;
  34. for (const condition of conditions) {
  35. if (!condition(doc)) {
  36. allConditionsMet = false;
  37. break;
  38. }
  39. }
  40. resolve(allConditionsMet);
  41. } catch (error) {
  42. reject(error);
  43. }
  44. });
  45. }
  46. }
  47. // Example Condition Functions (can be extended)
  48. function hasTitle(doc) {
  49. return doc.title !== null && doc.title !== "";
  50. }
  51. function hasLink(doc) {
  52. const links = doc.getElementsByTagName('a');
  53. return links.length > 0;
  54. }
  55. function hasImage(doc) {
  56. const images = doc.getElementsByTagName('img');
  57. return images.length > 0;
  58. }
  59. // Usage Example:
  60. const validator = new HTMLValidator();
  61. const conditions = [hasTitle, hasLink, hasImage];
  62. const html1 = `
  63. <!DOCTYPE html>
  64. <html>
  65. <head>
  66. <title>My Page</title>
  67. <link rel="stylesheet" href="style.css">
  68. </head>
  69. <body>
  70. <h1>Hello World</h1>
  71. <p>This is a test.</p>
  72. <img src="image.jpg">
  73. </body>
  74. </html>
  75. `;
  76. const html2 = `
  77. <!DOCTYPE html>
  78. <html>
  79. <head>
  80. </head>
  81. <body>
  82. <h1>Hello World</h1>
  83. <p>This is a test.</p>
  84. </body>
  85. </html>
  86. `;
  87. validator.validateHTML(html1, conditions);
  88. validator.validateHTML(html2, conditions);
  89. validator.validateHTML(html1, conditions); //will be rate limited
  90. validator.validateHTML(html1, conditions); //will be rate limited

Add your comment