UNPKG

arayts

Version:

让 TypeScript 开发如丝般顺滑。ArayTS 提供了一套高效、优雅的算法工具集,包含常用的数据结构与算法实现,帮助开发者轻松构建可靠的应用程序。

34 lines (33 loc) 1.49 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.fuzzyFilter = void 0; var fuzzyFilter = function (userInput, data, fieldName, maxResults) { if (maxResults === void 0) { maxResults = 3; } // 将输入字符串拆分成多个子串 var inputSegments = userInput.split(/\s+/); // 计算每个数据项的匹配度 var itemsWithMatchCounts = data.map(function (item) { // 确保字段存在且不为 undefined 或 null var fieldValue = item[fieldName]; if (fieldValue === undefined || fieldValue === null) { return { item: item, totalMatchCount: 0 }; } // 计算总匹配度 var totalMatchCount = inputSegments.reduce(function (count, segment) { var escapedSegment = segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); var regex = new RegExp(escapedSegment, 'iu'); var segmentMatchCount = (fieldValue.match(regex) || []).length; return count + segmentMatchCount; }, 0); return { item: item, totalMatchCount: totalMatchCount }; }); // 根据匹配度排序 itemsWithMatchCounts.sort(function (a, b) { return b.totalMatchCount - a.totalMatchCount; }); // 获取前 maxResults 个匹配项 var topMatchedItems = itemsWithMatchCounts.slice(0, maxResults).map(function (_a) { var item = _a.item; return item; }); return topMatchedItems; }; exports.fuzzyFilter = fuzzyFilter;