Skip to content

Commit c480be9

Browse files
committed
1 parent aac050a commit c480be9

File tree

3 files changed

+66
-1
lines changed

3 files changed

+66
-1
lines changed

Diff for: .npmrc

-1
Original file line numberDiff line numberDiff line change
@@ -1 +0,0 @@
1-
//registry.npmjs.org/:_authToken = ${NPM_TOKEN}

Diff for: src/validateCoords.test.js

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import validateCoords from './validateCoords';
2+
3+
const spy = jest.spyOn(console, 'error');
4+
5+
afterEach(() => {
6+
spy.mockRestore();
7+
});
8+
9+
describe('validateCoords', () => {
10+
it('should log errors in the console for invalid from/to coords', () => {
11+
validateCoords({ from: {}, to: {} });
12+
expect(spy).toHaveBeenCalledTimes(4);
13+
});
14+
15+
it('should NOT log errors in the console for valid from/to coords', () => {
16+
expect(spy).toHaveBeenCalledTimes(0);
17+
let from = { lat: 1, lng: 1 };
18+
let to = { lat: 2, lng: 2 };
19+
validateCoords({ from, to });
20+
expect(spy).toHaveBeenCalledTimes(0);
21+
from = { latitude: 1, longitude: 1 };
22+
to = { latitude: 2, longitude: 2 };
23+
validateCoords({ from, to });
24+
expect(spy).toHaveBeenCalledTimes(0);
25+
from = { latitude: 1, lon: 1 };
26+
to = { latitude: 2, lon: 2 };
27+
validateCoords({ from, to });
28+
expect(spy).toHaveBeenCalledTimes(0);
29+
});
30+
});

Diff for: src/validateCoords.ts

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
const lonKeys = ['lng', 'lon', 'longitude'];
2+
const latKeys = ['lat', 'latitude'];
3+
const typesRegex = /number|string/;
4+
5+
const isLongValid = (arg) =>
6+
!!lonKeys.find((key) => (typeof arg[key]).match(typesRegex));
7+
8+
const isLatValid = (arg) =>
9+
!!latKeys.find((key) => (typeof arg[key]).match(typesRegex));
10+
11+
const reportInvalid = (arg, fromOrTo, latOrLong) =>
12+
console.error(
13+
`[geolib] -> Get distance -> ${latOrLong} invalid for object "${fromOrTo}". expected property lng, lon or longitude to be present and have type of string or number, but received:`,
14+
arg
15+
);
16+
17+
const validateLong = (arg, fromOrTo) => {
18+
if (!isLongValid(arg)) {
19+
reportInvalid(arg, fromOrTo, 'longitude');
20+
}
21+
};
22+
23+
const validateLat = (arg, fromOrTo) => {
24+
if (!isLatValid(arg)) {
25+
reportInvalid(arg, fromOrTo, 'latitude');
26+
}
27+
};
28+
29+
const validateCoords = ({ from, to }) => {
30+
validateLat(from, 'from');
31+
validateLong(from, 'from');
32+
validateLat(to, 'to');
33+
validateLong(to, 'to');
34+
};
35+
36+
export default validateCoords;

0 commit comments

Comments
 (0)