Today A long time ago I implemented the CPF (Physical Persons Register) validation algorithm in javascript and rust to demonstrate how it is possible to not execute a single variable declaration (considering that receiving a parameter does not count as a declaration) using the method chaining programming style.
let validate = (cpf) => cpf
.match(/\d/g)
.map(digito => parseInt(digito))
.map(
(digito, idx) => [
(10 - idx) * digito,
(11 - idx) * digito
])
.reduce(
(aggregate, digit, index) => [
aggregate[0] + (index < 9 ? digit[0] : 0),
aggregate[1] + (index < 10 ? digit[1] : 0)
],
[0, 0]
)
.map(sum => sum * 10 % 11)
.join("") === cpf.slice(-2);
console.log(validate("999.999.999-99"));
console.log(validate("999.999.999-98"));
// output:
// true
// falsefn main() {
let cpf = |cpf: &str| {
cpf.chars()
.filter_map(|c| c.to_digit(10).map(|x| x as usize))
.enumerate()
.map(|(i, v)| {
(
(i < 9).then_some((10 - i) * v).unwrap_or(0),
(i < 10).then_some((11 - i) * v).unwrap_or(0),
)
})
.reduce(|(a0, a1), (v0, v1)| (a0 + v0, a1 + v1))
.map(|(a, b)| (a * 10 % 11, b * 10 % 11))
.map(|(a, b)| format!("{}{}", a, b))
.map(|a| a == cpf[cpf.len() - 2..])
.unwrap_or(false)
};
assert_eq!(cpf("999.999.999-99"), true);
assert_eq!(cpf("999.999.999-98"), false);
}