Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/cl/rut.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,18 @@ import {
} from '../exceptions';

describe('cl/rut', () => {
it('format:800280610', () => {
it('format:125319092', () => {
const result = format('125319092');

expect(result).toEqual('12.531.909-2');
});

it('format:77272305', () => {
const result = format('77272305');

expect(result).toEqual('7.727.230-5');
});

it('validate:76086428-5', () => {
const result = validate('76086428-5');

Expand Down
4 changes: 1 addition & 3 deletions src/cl/rut.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,7 @@ const impl: Validator = {
format(input: string): string {
const [value] = clean(input);

const [a, b, c, d] = strings.splitAt(value, 2, 5, 8);

return `${a}.${b}.${c}-${d}`;
return `${value.slice(0, -7)}.${value.slice(-7, -4)}.${value.slice(-4, -1)}-${value.slice(-1)}`;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

While the use of multiple slice() calls is correct, it can be a bit difficult to read and verify the indices at a glance. A regular expression can make this formatting logic more declarative and easier to understand. It also has the benefit of not producing a malformed string if the input doesn't match the expected RUT structure (e.g., for inputs with an incorrect length).

Suggested change
return `${value.slice(0, -7)}.${value.slice(-7, -4)}.${value.slice(-4, -1)}-${value.slice(-1)}`;
return value.replace(/^(\d{1,2})(\d{3})(\d{3})(.)$/, '$1.$2.$3-$4');

},

/**
Expand Down