UNPKG

quran-meta

Version:

Library with meta data and functionality related to Holy Quran

65 lines (64 loc) 2.05 kB
import { isValidAyahNo, isValidSurah } from "./typeGuards.mjs"; import { checkValidAyahId, checkValidSurahAyah } from "./validation.mjs"; export function ayahStringSplitter(str, isStrict = true) { const result = isStrict ? string2NumberSplitterStrict(str) : string2NumberSplitter(str); if (!result) { throw new Error("Invalid string format: " + str); } const { surahOrAyah: surahX, ayah, ayahTo } = result; if (!isValidSurah(surahX)) { throw new Error("Invalid ayah number: " + str); } const surah = surahX; let ayahs; if (ayahTo) { checkValidAyahId(ayah); checkValidAyahId(ayahTo); if (ayah > ayahTo) throw new Error("Invalid ayah range: " + str); ayahs = [ayah, ayahTo]; } else { if (!isValidAyahNo(ayah)) { throw new Error("Error in data " + str); } checkValidSurahAyah(surah, ayah); ayahs = ayah; } return [surah, ayahs]; } export function string2NumberSplitter(str) { const sr = /(?<surah>\d{1,3})\D*(?<ayah>\d{0,3})\D*(?<ayahTo>\d{0,3})/.exec(str); if (sr?.groups && +sr.groups.surah > 0) { const { ayah, ayahTo, surah } = sr.groups; return { surahOrAyah: +surah, ayah: +ayah, ayahTo: +ayahTo }; } return null; } export function string2NumberSplitterStrict(str) { let [surahStr, ayahsStr] = str.trim().split(":"); surahStr = surahStr.trim(); const surahX = parseInt(surahStr.trim(), 10); if (isNaN(surahX)) { throw new Error("Error in surah format " + str); } ayahsStr = ayahsStr.trim(); if (!ayahsStr) { throw new Error("Error in data " + str); } let ayahs; if (ayahsStr.includes("-")) { ayahs = ayahsStr.split("-").map((a) => { const ayahX = parseInt(a, 10); if (isNaN(ayahX)) { throw new Error("Error in surah format " + str); } return ayahX; }); } else { const ayahX = parseInt(ayahsStr, 10); if (isNaN(ayahX)) { throw new Error("Error in surah format " + str); } ayahs = [ayahX, NaN]; } return { surahOrAyah: +surahX, ayah: +ayahs[0], ayahTo: +ayahs[1] }; }