|
|
import{scoreValue as t,iterate as e,cmp as r,propToArray as i,getAttrNesting as n,getAttr as s}from"./utils.js";import{escape_regex as o,getPattern as c}from"@orchidjs/unicode-variants";export{getPattern}from"@orchidjs/unicode-variants";import"./types.js";class Sifter{items;settings;constructor(t,e){this.items=t;this.settings=e||{diacritics:true}}tokenize(t,e,r){if(!t||!t.length)return[];const i=[];const n=t.split(/\s+/);var s;r&&(s=new RegExp("^("+Object.keys(r).map(o).join("|")+"):(.*)$"));n.forEach((t=>{let r;let n=null;let u=null;if(s&&(r=t.match(s))){n=r[1];t=r[2]}if(t.length>0){u=this.settings.diacritics?c(t)||null:o(t);u&&e&&(u="\\b"+u)}i.push({string:t,regex:u?new RegExp(u,"iu"):null,field:n})}));return i}
|
|
|
*/_getScoreFunction(r){const i=r.tokens,n=i.length;if(!n)return function(){return 0};const s=r.options.fields,o=r.weights,c=s.length,u=r.getAttrFn;if(!c)return function(){return 1};const f=function(){return c===1?function(e,r){const i=s[0].field;return t(u(r,i),e,o[i]||1)}:function(r,i){var n=0;if(r.field){const e=u(i,r.field);!r.regex&&e?n+=1/c:n+=t(e,r,1)}else e(o,((e,s)=>{n+=t(u(i,s),r,e)}));return n/c}}();return n===1?function(t){return f(i[0],t)}:r.options.conjunction==="and"?function(t){var e,r=0;for(let n of i){e=f(n,t);if(e<=0)return 0;r+=e}return r/n}:function(t){var r=0;e(i,(e=>{r+=f(e,t)}));return r/n}}getSortFunction(t,e){var r=this.prepareSearch(t,e);return this._getSortFunction(r)}_getSortFunction(t){var e,i=[];const n=this,s=t.options,o=!t.query&&s.sort_empty?s.sort_empty:s.sort;if(typeof o=="function")return o.bind(this);const get_field=function(e,r){return e==="$score"?r.score:t.getAttrFn(n.items[r.id],e)};if(o)for(let e of o)(t.query||e.field!=="$score")&&i.push(e);if(t.query){e=true;for(let t of i)if(t.field==="$score"){e=false;break}e&&i.unshift({field:"$score",direction:"desc"})}else i=i.filter((t=>t.field!=="$score"));const c=i.length;return c?function(t,e){var n,s;for(let o of i){s=o.field;let i=o.direction==="desc"?-1:1;n=i*r(get_field(s,t),get_field(s,e));if(n)return n}return 0}:null}prepareSearch(t,e){const r={};var o=Object.assign({},e);i(o,"sort");i(o,"sort_empty");if(o.fields){i(o,"fields");const t=[];o.fields.forEach((e=>{typeof e=="string"&&(e={field:e,weight:1});t.push(e);r[e.field]="weight"in e?e.weight:1}));o.fields=t}return{options:o,query:t.toLowerCase().trim(),tokens:this.tokenize(t,o.respect_word_boundaries,r),total:0,items:[],weights:r,getAttrFn:o.nesting?n:s}}search(t,r){var i,n,s=this;n=this.prepareSearch(t,r);r=n.options;t=n.query;const o=r.score||s._getScoreFunction(n);t.length?e(s.items,((t,e)=>{i=o(t);(r.filter===false||i>0)&&n.items.push({score:i,id:e})})):e(s.items,((t,e)=>{n.items.push({score:1,id:e})}));const c=s._getSortFunction(n);c&&n.items.sort(c);n.total=n.items.length;typeof r.limit==="number"&&(n.items=n.items.slice(0,r.limit));return n}}export{Sifter,r as cmp,s as getAttr,n as getAttrNesting,e as iterate,i as propToArray,t as scoreValue};
|