|
| 1 | +import { fetchAuthToken, fetchCoffeeShops } from './api.js'; |
| 2 | + |
| 3 | +/** |
| 4 | + * Retry callback function with exponential backoff. |
| 5 | + * Used when fetching data fails |
| 6 | + * |
| 7 | + * @param {Function} callback - async function to retry |
| 8 | + * @param {number} maxRetries - maximum number of retries (default 3) |
| 9 | + * @param {number} initialDelay - initial delay in ms (default 1000) |
| 10 | + * @returns {Promise} |
| 11 | + */ |
| 12 | +export const retry = async (callback, maxRetries = 3, initialDelay = 1000) => { |
| 13 | + let lastError; |
| 14 | + |
| 15 | + for (let attempt = 0; attempt <= maxRetries; attempt++) { |
| 16 | + try { |
| 17 | + return await callback(); |
| 18 | + } catch (error) { |
| 19 | + lastError = error; |
| 20 | + |
| 21 | + if (attempt < maxRetries) { |
| 22 | + const delay = initialDelay * Math.pow(2, attempt); |
| 23 | + |
| 24 | + console.error( |
| 25 | + `Attempt ${attempt + 1} failed. Retrying in ${ |
| 26 | + delay / 1000 |
| 27 | + } seconds...` |
| 28 | + ); |
| 29 | + |
| 30 | + // wait before next retry |
| 31 | + await new Promise((resolve) => setTimeout(resolve, delay)); |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + throw lastError; |
| 37 | +}; |
| 38 | + |
| 39 | +/** |
| 40 | + * Calculate the distance between the user and a coffee shop using the Euclidean distance formula |
| 41 | + * |
| 42 | + * @param {{x: number, y: number}} userPosition |
| 43 | + * @param {{x: number, y: number}} shopPosition |
| 44 | + * @returns {number} distance between user and coffee shop rounded to 4 decimals |
| 45 | + */ |
| 46 | +export const getDistance = (userPosition, shopPosition) => { |
| 47 | + const distX = userPosition.x - shopPosition.x; |
| 48 | + const distY = userPosition.y - shopPosition.y; |
| 49 | + |
| 50 | + return Math.sqrt(distX * distX + distY * distY).toFixed(4); |
| 51 | +}; |
| 52 | + |
| 53 | +/** |
| 54 | + * Get the coffe shops data |
| 55 | + * |
| 56 | + * @returns {Promise<Array<{id: number, name: string, x: string, y: string, created_at: string, updated_at: string}>>} array of coffee shops |
| 57 | + */ |
| 58 | +export const getData = async () => { |
| 59 | + const token = await fetchAuthToken(); |
| 60 | + const coffeeShops = await fetchCoffeeShops(token); |
| 61 | + |
| 62 | + return coffeeShops; |
| 63 | +}; |
| 64 | + |
| 65 | +/** |
| 66 | + * Check if position has x and y coordinates as numbers |
| 67 | + * |
| 68 | + * @param {{x: number, y: number}} position |
| 69 | + */ |
| 70 | +export const isPositionValid = (position) => { |
| 71 | + const { x, y } = position; |
| 72 | + |
| 73 | + return !isNaN(x) && !isNaN(y); |
| 74 | +}; |
0 commit comments