UNPKG

@cristiansantana/chile-rut

Version:

Javascript (Typescript ready) chilean RUT toolset: Validate, generate and verify format.

90 lines (88 loc) 2.75 kB
// src/normalizers.ts var getNormalizedRutId = (rutNumber) => { if (!validateRutIdFormat(rutNumber)) { throw new Error("Error: RUT Number has non valid format"); } const digitRegex = /^\d$/; const normalizedRut = rutNumber.split("").reduce((previous, current) => { if (current === "0" && !previous) { return ""; } if (digitRegex.test(current)) { return previous + current; } return previous; }, ""); if (normalizedRut === "") { throw new Error("Error: RUT Number has non valid format"); } return normalizedRut; }; var getNormalizedRutCheckDigit = (checkDigit) => { if (!validateRutCheckDigitFormat(checkDigit)) { throw new Error("Error: RUT Check Digit has non valid format"); } return checkDigit === "k" ? "K" : checkDigit; }; var getNormalizedRut = (rut) => { if (!validateRutFormat(rut)) { throw new Error("Error: RUT has non valid format"); } const components = rut.split("-"); return getNormalizedRutId(components[0]) + "-" + getNormalizedRutCheckDigit(components[1]); }; // src/validators.ts var validateRutFormat = (rut) => { const validRegex = /^([0-9]{1,3}(\.[0-9]{3})*|[0-9]{1,3}(,[0-9]{3})*|[0-9]+)-(k|K|[0-9])$/; return validRegex.test(rut); }; var validateRutIdFormat = (rut) => { const validRegex = /^([0-9]{1,3}(\.[0-9]{3})*|[0-9]{1,3}(,[0-9]{3})*|[0-9]+)$/; return validRegex.test(rut); }; var validateRutCheckDigitFormat = (checkDigit) => { const validRegex = /^(k|K|[0-9])$/; return validRegex.test(checkDigit); }; var validateRut = (rut) => { if (!validateRutFormat(rut)) { return false; } const normalizedRut = getNormalizedRut(rut); const components = normalizedRut.split("-"); const id = components[0]; const checkDigit = components[1]; return checkDigit === getCheckDigit(id); }; // src/utilities.ts var getCheckDigit = (rutId) => { if (!validateRutIdFormat(rutId)) { throw new Error("Error: Rut Id has a non valid format"); } const normalizedRutId = getNormalizedRutId(rutId); const backwardsRut = normalizedRutId.split("").reverse(); const factors = [2, 3, 4, 5, 6, 7]; const sum = backwardsRut.reduce((previous, current, index) => { const factorIndex = (factors.length + index) % factors.length; return previous + parseInt(current) * factors[factorIndex]; }, 0); const quotient = Math.floor(sum / 11); const subtrahend1 = quotient * 11; const subtrahend2 = Math.abs(sum - subtrahend1); const digit = 11 - subtrahend2; if (digit === 11) { return "0"; } if (digit === 10) { return "K"; } return digit.toFixed(0); }; export { getCheckDigit, validateRut, validateRutCheckDigitFormat, validateRutFormat, validateRutIdFormat }; //# sourceMappingURL=index.js.map