Skip to content

Instantly share code, notes, and snippets.

@albovieira
Last active March 9, 2018 23:05
Show Gist options
  • Save albovieira/5ccff8543997da0ef9836ee0611f378b to your computer and use it in GitHub Desktop.
Save albovieira/5ccff8543997da0ef9836ee0611f378b to your computer and use it in GitHub Desktop.
Mod10 - Febraban
import _ from 'lodash';
function calculateDV(barcode) {
let brokeParts = _.chunk(barcode, 11);
if (barcode.startsWith(8)) {
return brokeParts
.map(i => {
let part = i.join('');
console.log(part);
return `${part}${mod10(part)}`;
})
.join('');
}
return convertBarcodeToDigitableLine(barcode);
}
function convertBarcodeToDigitableLine(code) {
var field1, field2, field3, field4, field5;
if (code.length != 44) {
return null; // 'A code do Código de Barras está incompleta!'
}
field1 =
code.substring(0, 4) + code.substring(19, 20) + +code.substring(20, 24);
field2 = code.substring(24, 29) + code.substring(29, 34);
field3 = code.substring(34, 39) + code.substring(39, 44);
field4 = code.substring(4, 5); // Digito verificador
field5 = code.substring(5, 19); // Vencimento + Valor
if (mod11(code.substring(0, 4) + code.substring(5, 44)) != field4) {
return null; //'Digito verificador '+field4+', o correto é '+modulo11_banco( linha.substr(0,4)+linha.substr(5,99) )+'\nO sistema não altera automaticamente o dígito correto na quinta casa!'
}
return `${field1}${mod10(field1)}${field2}${mod10(field2)}${field3}${mod10(
field3
)}${field4}${field5}`;
}
function mod10(number) {
var i,
mult = 2,
soma = 0,
ref = '';
for (i = number.length - 1; i >= 0; i--) {
ref = mult * parseInt(number.charAt(i)) + ref;
if (--mult < 1) {
mult = 2;
}
}
for (i = 0; i < ref.length; i++) {
soma = soma + parseInt(ref.charAt(i));
}
soma = soma % 10;
if (soma != 0) {
soma = 10 - soma;
}
return soma.toString();
}
function mod11(digits) {
if (typeof digits === 'string') {
digits = digits.split('');
}
digits.reverse();
var sum = 0;
for (var i = 0; i < digits.length; i++) {
sum += (i % 8 + 2) * digits[i];
}
return (11 - sum % 11) % 10 || 1;
}
export { calculateDV };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment