UNPKG

digipinjs

Version:

A comprehensive TypeScript library for encoding and decoding Indian geographic coordinates into DIGIPIN format (Indian Postal Digital PIN system). Features CLI tools, caching, batch processing, and Express middleware for seamless integration.

64 lines (63 loc) 2.42 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.generateGrid = generateGrid; const fs_1 = __importDefault(require("fs")); const core_1 = require("./core"); function assertStep(step) { if (step <= 0) { throw new RangeError('Step must be greater than zero'); } } function assertBounds(minLat, maxLat, minLng, maxLng) { if (minLat > maxLat) { throw new RangeError('minLat must be less than or equal to maxLat'); } if (minLng > maxLng) { throw new RangeError('minLng must be less than or equal to maxLng'); } } function* iterateGrid(minLat, maxLat, minLng, maxLng, step) { for (let lat = minLat; lat <= maxLat + 1e-9; lat += step) { for (let lon = minLng; lon <= maxLng + 1e-9; lon += step) { yield { lat, lon }; } } } function generateGrid(minLat, minLng, maxLat, maxLng, step, outFile, options = {}) { assertStep(step); assertBounds(minLat, maxLat, minLng, maxLng); const { outputFormat = 'ndjson', pretty = false, ...encodeOptions } = options; const fileDescriptor = fs_1.default.openSync(outFile, 'w'); if (outputFormat === 'json') { fs_1.default.writeSync(fileDescriptor, '{\n'); } let firstEntry = true; for (const { lat, lon } of iterateGrid(minLat, maxLat, minLng, maxLng, step)) { const pin = (0, core_1.getDigiPin)(lat, lon, encodeOptions); const key = `${lat.toFixed(6)},${lon.toFixed(6)}`; const payload = JSON.stringify({ key, pin }); if (outputFormat === 'ndjson') { fs_1.default.writeSync(fileDescriptor, payload); fs_1.default.writeSync(fileDescriptor, '\n'); continue; } if (!firstEntry) { fs_1.default.writeSync(fileDescriptor, ',\n'); } const record = pretty ? ` "${key}": ${JSON.stringify(pin)}` : `"${key}":${JSON.stringify(pin)}`; fs_1.default.writeSync(fileDescriptor, record); firstEntry = false; } if (outputFormat === 'json') { if (!firstEntry && pretty) { fs_1.default.writeSync(fileDescriptor, '\n'); } fs_1.default.writeSync(fileDescriptor, '}\n'); } fs_1.default.closeSync(fileDescriptor); }