function validarNIF(nif) {
    nif = nif.replace(/\s+/g, '');
    if (!/^\d{9}$/.test(nif)) return false;
    if (nif.charAt(0) === '0') return false;
    let soma = 0;
    for (let i = 0; i < 8; i++) {
        soma += parseInt(nif.charAt(i), 10) * (9 - i);
    }
    const resto = soma % 11;
    const digitoControlo = (resto === 0 || resto === 1) ? 0 : (11 - resto);
    return digitoControlo === parseInt(nif.charAt(8), 10);
}
console.log(validarNIF('509442013')); // valid NIF (e.g. some company)
console.log(validarNIF('213340058')); // valid random
console.log(validarNIF('200000000')); // invalid
