dika/src/lib.js
2026-11-16 13:06:11 +05:00

48 lines
1.9 KiB
JavaScript

export const MAX_KM = 5;
const TZ_OFFSET_H = 5; // Астана, UTC+5
export function distanceM(aLat, aLng, bLat, bLng) {
const R = 6371000, rad = (d) => (d * Math.PI) / 180;
const dLat = rad(bLat - aLat), dLng = rad(bLng - aLng);
const h = Math.sin(dLat / 2) ** 2 + Math.cos(rad(aLat)) * Math.cos(rad(bLat)) * Math.sin(dLng / 2) ** 2;
return Math.round(2 * R * Math.asin(Math.sqrt(h)));
}
// now → { day: 1..7 (пн..вс), minutes, date: YYYY-MM-DD } по времени Астаны
export function astanaTime(now = new Date()) {
const t = new Date(now.getTime() + TZ_OFFSET_H * 3600000);
return { day: t.getUTCDay() || 7, minutes: t.getUTCHours() * 60 + t.getUTCMinutes(), date: t.toISOString().slice(0, 10) };
}
const toMin = (s) => { const [h, m] = s.split(":").map(Number); return h * 60 + m; };
export function activeLunch(v, t) {
const l = v.lunch;
if (!l || !l.days.includes(t.day)) return null;
if (t.minutes < toMin(l.from) || t.minutes >= toMin(l.to)) return null;
return { price: l.price, from: l.from, to: l.to };
}
export function activePromo(v, t) {
return v.promo && v.promo.until >= t.date ? { text: v.promo.text, until: v.promo.until } : null;
}
export function buildList(venues, lat, lng, { only = false, now = new Date() } = {}) {
const t = astanaTime(now);
let list = venues.map((v) => ({
id: v.id, name: v.name, address: v.address,
distance: distanceM(lat, lng, v.lat, v.lng),
lunch: activeLunch(v, t), promo: activePromo(v, t),
}));
if (!list.some((v) => v.distance <= MAX_KM * 1000)) return [];
list = list.filter((v) => v.distance <= MAX_KM * 1000);
if (only) list = list.filter((v) => v.lunch || v.promo);
return list.sort((a, b) => a.distance - b.distance);
}
export function findAddress(venues, q) {
const s = q.trim().toLowerCase();
if (s.length < 3) return null;
return venues.find((v) => v.address.toLowerCase().includes(s)) || null;
}