Jump to content

User:Suffusion of Yellow/wikilint-worker.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
let checks = [];
let oldText = "";

onmessage = function(event) {
	if (event.data.action == "setup") {
		checks = event.data.checks;
		oldText = event.data.oldText;
		for(let check of checks)
			check.regexp = new RegExp(check.pattern, check.ignoreCase ? "ig" : "g");
	} else if (event.data.action == "getAnnotations")
		postMessage({
			id : event.data.id,
			annotations : getAnnotations(event.data.text)
		});
}

function getAnnotations(text, cb) {
	let start = performance.now();
	let lines = text.split("\n"), annotations = [];

	for(let line = 0; line < lines.length; line++) {
		for(let check of checks) {
			let match;

			check.regexp.lastIndex = 0;

			while( (match = check.regexp.exec(lines[line])) !== null) {
				annotations.push({
					from: [line, match.index],
					to: [line, match.index + match[0].length],
					message: check.message || "",
					messageParams: [ null, match[0] ],
					severity: check.severity || "warning",
					added: !oldText.includes(match[0]),
				});
			}
		}
	}

	console.log(`wikilint: Generated ${annotations.length} annotations from ${text.length} bytes in ${performance.now() - start} milliseconds`);

	return annotations;
}