update util.js

main
MohammadHoseinPaymard 2 weeks ago
parent be9d113eb2
commit e1327a9b35
  1. 191
      util.js

@ -201,9 +201,200 @@ function checkingOptions({ question, answer }) {
} }
return true; return true;
} }
async function checkingConditionTypes({ fQ, question, mojazData = [], answer }) {
let check = false, checkOption = false, inputType = 10;
let condition = {}, isRequired = null;
let requiredCondition = {}, validation = null;
requiredCondition = question?.requiredCondition || {};
validation = question?.validation || null;
condition = convertStringToJson(fQ?.condition) || convertStringToJson(question?.condition) || null;
isRequired = returnBooleanOfArguments([fQ?.isRequired, question?.required]);
inputType = question?.inputType || 10;
console.log("question id:", question.id)
console.log("requiredCondition", requiredCondition);
// console.log("validation",validation);
console.log("condition", condition);
console.log("isRequired", isRequired);
// console.log("options",options);
console.log("inputType", inputType);
//1.check requiredConditions
//2.check Conditions and check they required or not
//3.check Options and check they required or not
//4.check validation
//5.remove extra data
//1.check requiredConditions
check = checkCondition({ data: answer, condition: requiredCondition })
if (check.ok === false) throw `${defects[question.id]}`;
mojazData = [...new Set([...mojazData, ...check.conditionArray])];
console.log("DONE SOLVE requiredConditions")
//2.check Conditions and check they required or not
check = checkCondition({ data: answer, condition: condition })
checkOption = checkingOptions({ question, answer });
if ((check.ok === false || checkOption.ok === false) && isRequired === true) throw `${defects[question.id]}`;
if (checkOption.ok === true) mojazData.push(`${question.id}`);
mojazData = [...new Set([...mojazData, ...check.conditionArray])];
console.log("DONE SOLVE condition")
//3.check Validation (ro bayad beporsam az aghaye sadeghi)
console.log("mojazDataAfter-requiredCondition-condition", mojazData);
return {
mojazData
}
}
function isBoolean(value) {
if(typeof value==="string"){
if(value?.trim()?.toLowerCase()=="true") value=true;
else if(value?.trim()?.toLowerCase()=="false") value=false;
}
return typeof value === 'boolean';
}
function safeRegexFromString(regexString) {
try {
const parts = regexString.split('/');
if (parts.length < 3) {
// اگر / وجود نداشت، کل رشته به عنوان pattern در نظر گرفته میشود
return new RegExp(regexString);
}
const pattern = parts.slice(1, -1).join('/'); // برای الگوهایی که شامل / هستند
const flags = parts[parts.length - 1];
return new RegExp(pattern, flags);
} catch (error) {
console.error("Invalid regex string:", error);
// return null;
throw `invalidRegexFrom:${regexString}`;
}
}
function returnBooleanOfArguments(array){
if(!Array.isArray(array)) return false;
for(let i of array){
if(isBoolean(i)) return !!i;
}
return false;
}
function isNumber(value) {
// return typeof value === 'number' && !isNaN(value) && isFinite(value);
// return !isNaN(parseInt(value)) && isFinite(value);
return !isNaN(+value) && isFinite(+value);
}
function parseValue(value) {
// اگر ورودی از قبل رشته نباشد، همان مقدار را برگردانیم.
if (typeof value !== 'string') {
return value;
}
const trimmed = value.trim();
// // بررسی مقادیر بولی
// if (trimmed.toLowerCase() === 'true') return true;
// if (trimmed.toLowerCase() === 'false') return false;
// بررسی null و undefined
if (trimmed.toLowerCase() === 'null') return null;
if (trimmed.toLowerCase() === 'undefined') return undefined;
// بررسی عدد
// اگر رشته به صورت عددی تفسیر شود (توجه کنید که isNaN('') === false، پس باید رشته خالی هم چک شود)
if (trimmed !== '' && isNumber(trimmed)) {
return Number(trimmed);
}
// بررسی تاریخ
// Date.parse در صورت عدم توانایی در تبدیل، مقدار NaN برمیگرداند.
const timestamp = Date.parse(trimmed);
if (!isNaN(timestamp)) {
return new Date(trimmed);
}
// بررسی آرایه یا شیء (در صورتی که رشته با { یا [ شروع و به ترتیب با } یا ] پایان یابد)
if (
(trimmed.startsWith('{') && trimmed.endsWith('}')) ||
(trimmed.startsWith('[') && trimmed.endsWith(']'))
) {
try {
return JSON.parse(trimmed);
} catch (e) {
// در صورت بروز خطا، به ادامه کد میرویم
}
}
// در نهایت اگر هیچ یک از شرایط بالا صدق نکرد،
// رشته اصلی را برمیگردانیم.
return value;
}
function isValidDateStrict(date) {
if (date instanceof Date && !isNaN(date.getTime())) {
return true;
}
if (typeof date === "string") {
const parsed = new Date(date);
return parsed instanceof Date && !isNaN(parsed.getTime());
}
return false;
}
function convertDaysToSeconds(days){
return days * 24 * 3600 * 1000;
}
function isValidRegex(str) {
try {
if (str.startsWith('/')) {
let endSlashIndex = -1;
let backslashCount = 0;
// شروع جستجو از ایندکس ۱ (بعد از اسلش اول)
for (let i = 1; i < str.length; i++) {
if (str[i] === '\\') {
backslashCount++;
} else {
if (str[i] === '/' && backslashCount % 2 === 0) {
endSlashIndex = i;
break;
}
backslashCount = 0;
}
}
// اگر اسلش پایانی پیدا نشد
if (endSlashIndex === -1) {
return false;
}
const pattern = str.slice(1, endSlashIndex);
const modifiers = str.slice(endSlashIndex + 1);
new RegExp(pattern, modifiers);
} else {
new RegExp(str);
}
return true;
} catch (e) {
return false;
}
}
module.exports = { module.exports = {
sleep, sleep,
convertStringToJson, convertStringToJson,
isValidRegex,
convertDaysToSeconds,
isValidDateStrict,
parseValue,
isNumber,
returnBooleanOfArguments,
safeRegexFromString,
isBoolean,
checkingConditionTypes,
checkingOptions, checkingOptions,
checkCondition checkCondition
} }
Loading…
Cancel
Save