Skip to content

Commit

Permalink
Convert to TypeScript
Browse files Browse the repository at this point in the history
  • Loading branch information
svenheden committed Dec 18, 2017
1 parent 5263cdd commit d1562df
Show file tree
Hide file tree
Showing 10 changed files with 355 additions and 92 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
node_modules
node_modules
dist
1 change: 1 addition & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
index.ts
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ $ npm install --save swedish-personal-identity-number-validator
## Usage

```js
const isValid = require('swedish-personal-identity-number-validator');
import { isValid } from 'swedish-personal-identity-number-validator';

isValid('foobar') // => false
```
Expand Down
46 changes: 0 additions & 46 deletions dist/index.js

This file was deleted.

37 changes: 0 additions & 37 deletions index.js

This file was deleted.

38 changes: 38 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const pattern = /^\d{6}(\d{2})?[+-]?\d{4}$/;

const hasCorrectChecksum = (input: string) => {
const sum = input
.split('')
.reverse()
.map(Number)
.map((x, i) => i % 2 ? x * 2 : x)
.map((x) => x > 9 ? x - 9 : x)
.reduce((x, y) => x + y);

return sum % 10 === 0;
};

const hasValidDate = (input: string) => {
let [_, yearStr, monthStr, dayStr] = /^(\d{2})(\d{2})(\d{2})/.exec(input);

const year = Number(yearStr);
const month = Number(monthStr) - 1;
const day = Number(dayStr);
const date = new Date(year, month, day);

const yearIsValid = String(date.getFullYear()).substr(-2) === yearStr;
const monthIsValid = date.getMonth() === month;
const dayIsValid = date.getDate() === day;

return yearIsValid && monthIsValid && dayIsValid;
};

export const isValid = (input: string) => {
if (!pattern.test(input)) {
return false;
}

const cleaned = input.replace(/[+-]/, '').slice(-10);

return hasCorrectChecksum(cleaned) && hasValidDate(cleaned);
};
Loading

0 comments on commit d1562df

Please sign in to comment.