class HTMLValidator {
constructor(rateLimit = { limit: 10, interval: 1000 }) {
this.rateLimit = rateLimit;
this.lastRun = 0;
this.queue = [];
}
validateHTML(html, conditions) {
const now = Date.now();
if (now - this.lastRun > this.rateLimit.interval) {
this.lastRun = now;
} else {
this.queue.push({ html, conditions });
return; // Rate limited, don't validate
}
this.validateQueue();
this.runValidation(html, conditions).then(result => {
console.log("Validation Result:", result);
}).catch(err => {
console.error("Validation Error:", err);
});
}
validateQueue() {
while (this.queue.length > 0) {
const item = this.queue.shift();
this.runValidation(item.html, item.conditions);
}
}
runValidation(html, conditions) {
return new Promise((resolve, reject) => {
try {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
let allConditionsMet = true;
for (const condition of conditions) {
if (!condition(doc)) {
allConditionsMet = false;
break;
}
}
resolve(allConditionsMet);
} catch (error) {
reject(error);
}
});
}
}
// Example Condition Functions (can be extended)
function hasTitle(doc) {
return doc.title !== null && doc.title !== "";
}
function hasLink(doc) {
const links = doc.getElementsByTagName('a');
return links.length > 0;
}
function hasImage(doc) {
const images = doc.getElementsByTagName('img');
return images.length > 0;
}
// Usage Example:
const validator = new HTMLValidator();
const conditions = [hasTitle, hasLink, hasImage];
const html1 = `
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Hello World</h1>
<p>This is a test.</p>
<img src="image.jpg">
</body>
</html>
`;
const html2 = `
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Hello World</h1>
<p>This is a test.</p>
</body>
</html>
`;
validator.validateHTML(html1, conditions);
validator.validateHTML(html2, conditions);
validator.validateHTML(html1, conditions); //will be rate limited
validator.validateHTML(html1, conditions); //will be rate limited
Add your comment