UNPKG

ast-deep-contains

Version:

Like t.same assert on array of objects, where element order doesn't matter.

16 lines (14 loc) 2.09 kB
/** * @name ast-deep-contains * @fileoverview Like t.same assert on array of objects, where element order doesn't matter. * @version 5.0.23 * @author Roy Revelt, Codsen Ltd * @license MIT * {@link https://codsen.com/os/ast-deep-contains/} */ import h from"object-path";import{traverse as J}from"ast-monkey-traverse";import l from"@sindresorhus/is";var V="5.0.23";var F=V;function j(n){if(n.includes(".")){for(let s=n.length;s--;)if(n[s]===".")return n.slice(0,s)}return n}function k(n,s){return Array.from(n).filter((b,c)=>c!==s)}var x={skipContainers:!0,arrayStrictComparison:!1};function w(n,s,b,c,O){let f={...x,...O};l(n)!==l(s)?c(`the first input arg is of a type ${l(n).toLowerCase()} but the second is ${l(s).toLowerCase()}. Values are - 1st: ${JSON.stringify(n,null,4)} 2nd: ${JSON.stringify(s,null,4)}`):J(s,(D,E,a,v)=>{let d=E!==void 0?E:D,{path:$}=a;if(h.has(n,$))if(!f.arrayStrictComparison&&l.plainObject(d)&&a.parentType==="array"&&a.parent.length>1){v.now=!0;let o=Array.from(a.path.includes(".")?h.get(n,j($)):n);if(o.length<a.parent.length)c(`the first array: ${JSON.stringify(o,null,4)} has less objects than array we're matching against, ${JSON.stringify(a.parent,null,4)}`);else{let m=a.parent,g=o.map((e,r)=>r),A=m.map((e,r)=>r),S=[];for(let e=0,r=g.length;e<r;e++){let t=[],i=g[e],p=k(g,e);t.push(i),p.forEach(N=>{S.push(Array.from(t).concat(N))})}let u=S.map(e=>e.map((r,t)=>[t,r])),y=0;for(let e=0,r=u.length;e<r;e++){let t=0;u[e].forEach(i=>{l.plainObject(m[i[0]])&&l.plainObject(o[i[1]])&&Object.keys(m[i[0]]).forEach(p=>{Object.keys(o[i[1]]).includes(p)&&(t+=1,o[i[1]][p]===m[i[0]][p]&&(t+=5))})}),u[e].push(t),t>y&&(y=t)}for(let e=0,r=u.length;e<r;e++)if(u[e][2]===y){u[e].forEach((t,i)=>{i<u[e].length-1&&w(o[t[1]],m[t[0]],b,c,f)});break}}}else{let o=h.get(n,$);(!f.skipContainers||!l.plainObject(o)&&!Array.isArray(o))&&b(o,d,$)}else c(`the first input: ${JSON.stringify(n,null,4)} does not have the path "${$}", we were looking, would it contain a value ${JSON.stringify(d,null,0)}.`);return d})}export{w as deepContains,x as defaults,F as version};