Skip to content

Commit

Permalink
feat(number): add getKmRadius method
Browse files Browse the repository at this point in the history
  • Loading branch information
jlenon7 committed Apr 27, 2022
1 parent 5000afb commit d5f3d70
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/Number.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,37 @@ export class Number {
return Math.max.apply(Math, numbers)
}

/**
* Get km radius between two coordinates.
*
* @param {{ latitude: number, longitude: number }} centerCord
* @param {{ latitude: number, longitude: number }} pointCord
* @return {number}
*/
static getKmRadius(centerCord, pointCord) {
const deg2rad = deg => deg * (Math.PI / 180)

const radius = 6371

const { latitude: latitude1, longitude: longitude1 } = centerCord
const { latitude: latitude2, longitude: longitude2 } = pointCord

const dLat = deg2rad(latitude2 - latitude1)
const dLon = deg2rad(longitude2 - longitude1)

const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(deg2rad(latitude1)) *
Math.cos(deg2rad(latitude2)) *
Math.sin(dLon / 2) *
Math.sin(dLon / 2)

const center = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
const distance = radius * center

return distance
}

/**
* Get the lower number from an array of numbers.
*
Expand Down
14 changes: 14 additions & 0 deletions tests/Unit/NumberTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,20 @@ describe('\n Numbers Class', () => {
expect(higher).toBe(5)
})

it('should get km radius between two coordinates', () => {
const first = Number.getKmRadius(
{ latitude: -25503207, longitude: -545390592 },
{ latitude: -25503207, longitude: -545390592 },
)
const second = Number.getKmRadius(
{ latitude: -25503207, longitude: -545390592 },
{ latitude: -254957901, longitude: -545671577 },
)

expect(first).toBe(0)
expect(second).toBe(5338.683217695541)
})

it('should extract all numbers inside of a string in number and array format', () => {
const stringWithNumbers =
"My name is João Lenon and I've 20 years old and I've been living in Foz do Iguaçu for 18 years"
Expand Down

0 comments on commit d5f3d70

Please sign in to comment.