-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustomers.js
64 lines (55 loc) · 1.7 KB
/
customers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const fs = require('fs')
const deg2rad = (deg) => {
return deg * (Math.PI / 180)
}
const readFileContent = (fileName) => {
try {
return fs.readFileSync(fileName, 'utf-8')
} catch (error) {
console.error(error.code)
return
}
}
const isWithinDistance = (lat1, lng1, lat2, lng2, distance) => {
if (!lat1 || !lng1 || !lat2 || !lng2 || !distance) {
return false
}
const R = 6371 // Earth radius in km
const dLat = deg2rad(lat2 - lat1)
const dLon = deg2rad(lng2 - lng1)
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2)
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
return R * c <= distance
}
const customers = () => {
const latOffice = 53.339428
const lngOffice = -6.257664
const distanceInKM = 100
const fileContent = readFileContent('./customers.json')
let customers = {}
let userIDs = []
// storing close-by customers
fileContent && fileContent.split("\n").forEach(function (line) {
let customer = JSON.parse(line)
if (isWithinDistance(latOffice, lngOffice, customer.latitude, customer.longitude, distanceInKM)) {
customers[customer.user_id] = customer.name
userIDs.push(customer.user_id)
}
})
// sorting them by user_id asc
userIDs.sort((a, b) => { return a - b })
// printing their id and name
userIDs.forEach(function (key) {
console.log(`${key}: ${customers[key]}`)
});
}
// exporting functions for testing purposes
module.exports = {
customers,
deg2rad,
isWithinDistance,
readFileContent
}