function findDuplicateRulestype1and3(records = [], { flat = false } = {}) {
const seenKeys = new Map(); // key -> group key or representative record
const groupsMap = new Map(); // group key -> array of rules
const duplicateRecords = []; // for flat mode
code
Assistant
User
i said based on findduplicateruletype1and3 make changes in findducpliaterulestype4
Assistant
const stripHTML4 = (htmlString) => {
if (typeof htmlString !== "string") {
htmlString = String(htmlString || "");
}
const div = document.createElement("div");
div.innerHTML = htmlString.replace(/ /gi, " ");
function walkAndClean(node) {
let result = "";
for (const child of node.childNodes) {
if (child.nodeType === Node.TEXT_NODE) {
result += child.nodeValue;
} else if (child.nodeType === Node.ELEMENT_NODE) {
result += walkAndClean(child);
}
}
return result;
}
return walkAndClean(div)
.replace(/\u200B|\uFEFF|\u00A0/g, "")
.replace(/\./g, "")
.replace(/\s+/g, "")
.toLowerCase();
};
const normalizeConditionParts = (rawConditions) => {
console.log("✅ [normalizeConditionParts] rawConditions:", rawConditions);
console.log("ℹ️ Type of rawConditions:", typeof rawConditions);
const parts = typeof rawConditions === "string" ? rawConditions.split(",") : [];
if (typeof rawConditions !== "string") {
console.warn("⚠️ [normalizeConditionParts] Expected string but got:", typeof rawConditions, rawConditions);
}
const set1 = [], set2 = [];
let currentSet = null;
let tempClause = [];
const stripHTML4 = (htmlString) => {
if (typeof htmlString !== "string") htmlString = String(htmlString || "");
const div = document.createElement("div");
div.innerHTML = htmlString.replace(/ /gi, " ");
return div.textContent || div.innerText || "";
};
const pushClause = (targetSet, includeOperator = null) => {
if (tempClause.length && targetSet) {
const joinedClause = tempClause.join(",").trim();
const cleaned = stripHTML4(joinedClause);
console.log("📦 [pushClause] Cleaned clause:", cleaned);
if (cleaned) targetSet.push(cleaned);
tempClause = [];
if (includeOperator) {
console.log("➕ [pushClause] Operator pushed:", includeOperator);
targetSet.push(includeOperator);
}
}
};
const isSetMarker = (part) =>
part.includes("condition_set_1") || part.includes("condition_set_2");
const handleSetSwitch = (rawPart) => {
pushClause(currentSet);
if (rawPart.includes("condition_set_1")) return set1;
if (rawPart.includes("condition_set_2")) return set2;
return currentSet;
};
const isLogicalOperator = (part) => {
const op = part.toLowerCase();
return op === "any" || op === "all";
};
for (let i = 0; i < parts.length; i++) {
const rawPart = parts[i].trim();
if (isSetMarker(rawPart)) {
console.log("🔀 [Set Switch] Switching set for part:", rawPart);
currentSet = handleSetSwitch(rawPart);
} else if (isLogicalOperator(rawPart)) {
console.log("⚙️ [Operator] Found logical operator:", rawPart);
pushClause(currentSet, rawPart.toLowerCase());
} else if (currentSet) {
tempClause.push(rawPart);
}
}
pushClause(currentSet);
set1.sort();
set2.sort();
console.log("✅ Final set1:", set1);
console.log("✅ Final set2:", set2);
return { set1, set2 };
};
const normalizeActions = (rawActions) => {
if (typeof rawActions !== 'string' || !rawActions) {
return '';
}
const parts = rawActions.split("&?");
const normalizedClauses = [];
for (const part of parts) {
const items = part.split(",").map(v => stripHTML4(v));
const clause = items.sort().join(" ").trim();
if (clause) normalizedClauses.push(clause);
}
normalizedClauses.sort((a, b) => a.localeCompare(b));
return normalizedClauses.join(" | ");
};
for (const record of records) {
const data = record.data ?? record;
const { conditions = "", actions = "", operator = "", active } = data;
if (!(active === true || active === "true")) continue;
const { set1, set2 } = normalizeConditionParts(conditions);
const normalizedActions = normalizeActions(actions);
const normalizedOperator = stripHTML4(operator);
const key1 = `${set1.join("|")}|${set2.join("|")}|${normalizedActions}|${normalizedOperator}`;
const key2 = `${set2.join("|")}|${set1.join("|")}|${normalizedActions}|${normalizedOperator}`;
if (flat) {
// Flat duplicate logic
if (seenKeys.has(key1) || seenKeys.has(key2)) {
const existing = seenKeys.get(key1) || seenKeys.get(key2);
if (!duplicateRecords.includes(existing)) {
duplicateRecords.push(existing);
}
duplicateRecords.push(record);
} else {
seenKeys.set(key1, record);
}
} else {
// Grouped duplicate logic
if (seenKeys.has(key1)) {
const groupKey = seenKeys.get(key1);
groupsMap.get(groupKey).push(record);
} else if (seenKeys.has(key2)) {
const groupKey = seenKeys.get(key2);
groupsMap.get(groupKey).push(record);
} else {
seenKeys.set(key1, key1);
groupsMap.set(key1, [record]);
}
}
}
return flat
? duplicateRecords
: Array.from(groupsMap.values()).filter(group => group.length > 1);
}
in this, how did you fixed for conditoins and actions
function findDuplicateRulestype4(records = []) {
const seenRules = new Map(); // key => array of records with that key
const duplicateGroups = [];
for (const part of parts) {
const items = part.split(",").map((v) => stripHTML4(v));
const clause = items.sort().join(" ").trim();
if (clause) normalizedClauses.push(clause);
}
normalizedClauses.sort((a, b) => a.localeCompare(b));
return normalizedClauses.join(" | ");
};
// ✅ Filter only active records
const activeRecords = records.filter(
(record) => record?.active === true || record?.active === "true"
);
activeRecords.forEach((record, index) => {
if (!record || typeof record !== "object") {
console.warn(⚠️ Skipping invalid record at index ${index}, record);
return;
}
for (const group of seenRules.values()) {
if (group.length > 1) {
duplicateGroups.push(group);
}
}
return duplicateGroups;
}
same way fix in this too
Certainly! To fix findDuplicateRulestype1and3 in the same way as findDuplicateRulestype4, especially around the normalization of conditions and actions, you would:
Use a stripHTML4 function that strips HTML, Unicode zero-width spaces, non-breaking spaces, dots, extra whitespace, and lowercases the text.
Normalize condition parts, splitting on commas, grouping using sets, handling logical operators properly, cleaning clauses with the above strip function, and sorting.
Normalize actions by splitting on "&?", splitting parts by commas, cleaning, sorting, and joining with " | " delimiter.
Apply similar robust normalization for operator.
Additionally, you might want to ensure active filtering is consistent and keys are formed to identify duplicates by comparing with both set orders.
Here is your original function fixed with the approach borrowed from findDuplicateRulestype4:
js
function findDuplicateRulestype1and3(records = [], { flat = false } = {}) {
const seenKeys = new Map(); // key -> group key or representative record
const groupsMap = new Map(); // group key -> array of rules
const duplicateRecords = []; // for flat mode
const stripHTML4 = (htmlString) => {
if (typeof htmlString !== "string") {
htmlString = String(htmlString || "");
}
if (typeof document === "undefined") return htmlString;
const div = document.createElement("div");
div.innerHTML = htmlString.replace(/ /gi, " ");
function walkAndClean(node) {
let result = "";
for (const child of node.childNodes) {
if (child.nodeType === Node.TEXT_NODE) {
result += child.nodeValue;
} else if (child.nodeType === Node.ELEMENT_NODE) {
result += walkAndClean(child);
}
}
return result;
}
return walkAndClean(div)
.replace(/\u200B|\uFEFF|\u00A0/g, "") // zero-width spaces & no-break spaces
.replace(/\./g, "") // remove dots
.replace(/\s+/g, "") // remove all whitespace
.toLowerCase();
};
const normalizeConditionParts = (rawConditions) => {
const parts = typeof rawConditions === "string" ? rawConditions.split(",") : [];
const set1 = [], set2 = [];
let currentSet = null;
let tempClause = [];
const pushClause = (targetSet, includeOperator = null) => {
if (tempClause.length && targetSet) {
const joinedClause = tempClause.join(",").trim();
const cleaned = stripHTML4(joinedClause);
if (cleaned) targetSet.push(cleaned);
tempClause = [];
if (includeOperator) {
targetSet.push(includeOperator);
}
}
};
const isSetMarker = (part) =>
part.includes("condition_set_1") || part.includes("condition_set_2");
const handleSetSwitch = (rawPart) => {
pushClause(currentSet);
if (rawPart.includes("condition_set_1")) return set1;
if (rawPart.includes("condition_set_2")) return set2;
return currentSet;
};
const isLogicalOperator = (part) => {
const op = part.toLowerCase();
return op === "any" || op === "all";
};
for (let i = 0; i < parts.length; i++) {
const rawPart = parts[i].trim();
if (isSetMarker(rawPart)) {
currentSet = handleSetSwitch(rawPart);
} else if (isLogicalOperator(rawPart)) {
pushClause(currentSet, rawPart.toLowerCase());
} else if (currentSet) {
tempClause.push(rawPart);
}
}
pushClause(currentSet);
set1.sort();
set2.sort();
return { set1, set2 };
};
const normalizeActions = (rawActions) => {
if (typeof rawActions !== "string" || !rawActions) {
return "";
}
const parts = rawActions.split("&?");
const normalizedClauses = [];
for (const part of parts) {
const items = part.split(",").map(v => stripHTML4(v));
const clause = items.sort().join(" ").trim();
if (clause) normalizedClauses.push(clause);
}
normalizedClauses.sort((a, b) => a.localeCompare(b));
return normalizedClauses.join(" | ");
};
for (const record of records) {
const data = record.data ?? record;
const { conditions = "", actions = "", operator = "", active } = data;
if (!(active === true || active === "true")) continue;
const { set1, set2 } = normalizeConditionParts(conditions);
const normalizedActions = normalizeActions(actions);
const normalizedOperator = stripHTML4(operator);
const key1 = `${set1.join("|")}|${set2.join("|")}|${normalizedActions}|${normalizedOperator}`;
const key2 = `${set2.join("|")}|${set1.join("|")}|${normalizedActions}|${normalizedOperator}`;
if (flat) {
if (seenKeys.has(key1) || seenKeys.has(key2)) {
const existing = seenKeys.get(key1) || seenKeys.get(key2);
if (!duplicateRecords.includes(existing)) {
duplicateRecords.push(existing);
}
duplicateRecords.push(record);
} else {
seenKeys.set(key1, record);
}
} else {
if (seenKeys.has(key1)) {
const groupKey = seenKeys.get(key1);
groupsMap.get(groupKey).push(record);
} else if (seenKeys.has(key2)) {
const groupKey = seenKeys.get(key2);
groupsMap.get(groupKey).push(record);
} else {
seenKeys.set(key1, key1);
groupsMap.set(key1, [record]);
}
}
}
return flat
? duplicateRecords
: Array.from(groupsMap.values()).filter(group => group.length > 1);
}
Summary of Fixes:
stripHTML4 improvements:
Added zero-width space and no-break space removal.
Removed dots and all whitespaces.
Lowercased everything.
normalizeConditionParts:
Robust parsing: split conditions by comma, group into sets (set1, set2).
For each clause: join, clean using stripHTML4, push into the appropriate set.
Sort the sets after construction.
normalizeActions:
Split by "&?" delimiter (multiple clauses).
Split each clause by ,, clean, sort, join by space.
Sort all clauses, join by " | " to produce a unique normalized string.
Key construction uses normalized sets for conditions, normalized string for actions and normalized operator (using stripHTML4).
It detects duplicates by checking keys with symmetric order of sets (key1 vs key2).
This makes findDuplicateRulestype1and3 align well with the normalization approach you successfully used in findDuplicateRulestype4. This ensures that duplicate detection is robust against unordered conditions, HTML artifacts, spacing, punctuation, casing, and multiple action clauses.
Got it! You want to fix findDuplicateRulestype4 by adopting the style and approach of findDuplicateRulestype1and3****. The main differences to adopt from findDuplicateRulestype1and3 are:
Use the more advancedstripHTML4 that handles HTML stripping, zero-width/no-break spaces, dots, spaces, lowercasing
Use the normalizeConditionParts that processes conditions with split by commas, sets, logical operators, HTML stripped and sorted clauses
Use a simplified and robust normalizeActions that splits on "&?", processes clauses, strips HTML, sorts and joins with " | "
Use similar operator normalization with stripHTML4
Keep key generation with symmetrical condition sets
Filtering by active properly
Consistent structure and logic
Here's an adapted and fixed version of findDuplicateRulestype4 aligned with the style from findDuplicateRulestype1and3:
js
function findDuplicateRulestype4(records = []) {
const seenRules = new Map(); // key -> array of records
const duplicateGroups = [];
// Same advanced stripHTML4 as in type1and3
const stripHTML4 = (htmlString) => {
if (typeof htmlString !== "string") {
htmlString = String(htmlString || "");
}
if (typeof document === "undefined") return htmlString;
const div = document.createElement("div");
div.innerHTML = htmlString.replace(/ /gi, " ");
function walkAndClean(node) {
let result = "";
for (const child of node.childNodes) {
if (child.nodeType === Node.TEXT_NODE) {
result += child.nodeValue;
} else if (child.nodeType === Node.ELEMENT_NODE) {
result += walkAndClean(child);
}
}
return result;
}
return walkAndClean(div)
.replace(/\u200B|\uFEFF|\u00A0/g, "") // remove zero-width & no-break spaces
.replace(/\./g, "") // remove dots
.replace(/\s+/g, "") // remove all whitespace
.toLowerCase();
};
// Adopt normalizeConditionParts from type1and3 (handles splitting, sets, operators, etc)
const normalizeConditionParts = (rawConditions) => {
const parts = typeof rawConditions === "string" ? rawConditions.split(",") : [];
const set1 = [], set2 = [];
let currentSet = null;
let tempClause = [];
const pushClause = (targetSet, includeOperator = null) => {
if (tempClause.length && targetSet) {
const joinedClause = tempClause.join(",").trim();
const cleaned = stripHTML4(joinedClause);
if (cleaned) targetSet.push(cleaned);
tempClause = [];
if (includeOperator) {
targetSet.push(includeOperator);
}
}
};
const isSetMarker = (part) =>
part.includes("condition_set_1") || part.includes("condition_set_2");
const handleSetSwitch = (rawPart) => {
pushClause(currentSet);
if (rawPart.includes("condition_set_1")) return set1;
if (rawPart.includes("condition_set_2")) return set2;
return currentSet;
};
const isLogicalOperator = (part) => {
const op = part.toLowerCase();
return op === "any" || op === "all";
};
for (let i = 0; i < parts.length; i++) {
const rawPart = parts[i].trim();
if (isSetMarker(rawPart)) {
currentSet = handleSetSwitch(rawPart);
} else if (isLogicalOperator(rawPart)) {
pushClause(currentSet, rawPart.toLowerCase());
} else if (currentSet) {
tempClause.push(rawPart);
}
}
pushClause(currentSet);
set1.sort();
set2.sort();
return { set1, set2 };
};
// Simplified normalizeActions based on type1and3
const normalizeActions = (rawActions) => {
if (typeof rawActions !== "string" || !rawActions) {
return "";
}
const parts = rawActions.split("&?");
const normalizedClauses = [];
for (const part of parts) {
const items = part.split(",").map(v => stripHTML4(v));
const clause = items.sort().join(" ").trim();
if (clause) normalizedClauses.push(clause);
}
normalizedClauses.sort((a, b) => a.localeCompare(b));
return normalizedClauses.join(" | ");
};
// Operator normalization
const normalizeOperator = (operator) => stripHTML4(operator);
// Filter active records the same way
const activeRecords = records.filter(r => r?.active === true || r?.active === "true");
activeRecords.forEach((record, idx) => {
if (!record || typeof record !== "object") {
console.warn(`⚠️ Skipping invalid record at index ${idx}`, record);
return;
}
const { conditions = "", actions = "", operator = "", events = "", performer = "" } = record;
// Conditions normalized with new method
const { set1, set2 } = normalizeConditionParts(conditions);
// Actions normalized with new method
const normalizedActions = normalizeActions(actions);
// Operator normalized
const normalizedOp = normalizeOperator(operator);
// We can reuse previous normalization for events & performer or keep old if desired
// Here I'll reuse your old normalizations, but you can adapt similarly if needed.
const normalizedEvents = (typeof events === "string")
? events.split(/\s+or\s+/i).map(stripHTML4).sort().join(" or ")
: "";
const normalizeField = (value) => {
if (Array.isArray(value)) {
return value.map(item =>
Object.values(item).map(v => stripHTML4(v)).join(" ")
).sort().join(",");
} else if (typeof value === "string") {
return value.split(",").map(stripHTML4).sort().join(",");
}
return "";
};
const normalizedPerformer = normalizeField(performer);
// Construct keys (check both orders of sets to detect duplicates)
const key1 = `${set1.join("|")}|${set2.join("|")}|${normalizedActions}|${normalizedOp}|${normalizedEvents}|${normalizedPerformer}`;
const key2 = `${set2.join("|")}|${set1.join("|")}|${normalizedActions}|${normalizedOp}|${normalizedEvents}|${normalizedPerformer}`;
let groupKey = null;
if (seenRules.has(key1)) {
groupKey = key1;
} else if (seenRules.has(key2)) {
groupKey = key2;
}
if (groupKey) {
seenRules.get(groupKey).push(record);
} else {
seenRules.set(key1, [record]);
}
});
// Collect only groups with duplicates
for (const group of seenRules.values()) {
if (group.length > 1) duplicateGroups.push(group);
}
return duplicateGroups;
}
Summary of changes in findDuplicateRulestype4 per findDuplicateRulestype1and3 style:
Replaced stripHTML4 with the improved, thorough version from type1and3
Adopted normalizeConditionParts that parses condition split by comma, supports sets, logical ops, cleans & sorts - identical logic to type1and3
Simplified and aligned normalizeActions with type1and3 style: split on "&?", clean, sort, join with " | "
Operator normalization simplified using the advanced stripHTML4
Maintained filtering for active records consistently
Key builds with symmetrical checking of condition sets
Kept existing logic for events and performer normalization (but you can optionally unify them too)
Used consistent warnings for invalid records
If you'd like, I can help unify events and performer normalizations also into a similar style or further refine — just ask! But this code matches your request to fix findDuplicateRulestype4 based on the findDuplicateRulestype1and3 approach for conditions and actions normalization.