Last active
March 16, 2021 04:29
-
-
Save itolosa/221305aa4d61f3f6bb736e6afa83c3b9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function filterChars(dv: string): string { | |
let result = ''; | |
for (const c of dv) { | |
if ((c >= '0' && c <= '9') || c === 'k') { | |
result += c; | |
} | |
} | |
return result; | |
} | |
function normalizeRUT(chars: string): string { | |
return filterChars(chars.toLocaleLowerCase()); | |
} | |
function lastChar(str: string): string { | |
return str[str.length - 1]; | |
} | |
function removeLastChar(str: string): string { | |
return str.slice(0, -1); | |
} | |
function getWeight(j: number) { | |
return parseInt('234567'[(j - 1) % 6]); | |
} | |
function sumAB(a: number, b: number): number { | |
return a + b; | |
} | |
function weightedSum(rutWithoutDv: string) { | |
const n = rutWithoutDv.length; | |
return stringToArray(rutWithoutDv) | |
.map((digit, i) => getWeight(n - i) * parseInt(digit)) | |
.reduce(sumAB); | |
} | |
function stringToArray(rutWithoutDv: string) { | |
return rutWithoutDv.split(''); | |
} | |
function extractRutWithoutDV(fullRut: string) { | |
return removeLastChar(fullRut); | |
} | |
function extractDv(fullRut: string) { | |
return lastChar(fullRut); | |
} | |
function hasValidParams(rut: string, dv: string) { | |
return hasLessThanTwoChars(dv) && hasTwoOrMoreChars(dv + rut); | |
} | |
function hasTwoOrMoreChars(fullRut: string) { | |
const r = normalizeRUT(fullRut); | |
return r.length >= 2; | |
} | |
function hasLessThanTwoChars(dv: string) { | |
const d = normalizeRUT(dv); | |
return d.length <= 1; | |
} | |
function formatDv(d: number): string { | |
return d === 10 ? 'k' : d.toString(); | |
} | |
function validateRut(rut: string, dv = ''): boolean { | |
if (!hasValidParams(rut, dv)) return false; | |
const cleanRut = normalizeRUT(rut + dv); | |
const r = extractRutWithoutDV(cleanRut); | |
const d = extractDv(cleanRut); | |
return generateDv(r) === d; | |
} | |
function generateDv(rutWithoutDv: string): string { | |
const sum = weightedSum(rutWithoutDv); | |
const d = (11 - (sum % 11)) % 11; | |
return formatDv(d); | |
} | |
export { validateRut, generateDv }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment