I am trying to compare objects with specific properties or arrays with certain elements using the following code snippet:
However, I encountered a compilation error. Can anyone help me troubleshoot this issue?
type Pos = [number, number]
type STAR = "*"
type LITERAL<A> = A
type Matcher<A> = STAR | LITERAL<A>
function match<A>(s: A, m: Matcher<A>): boolean {
if (m === "*") {
return true;
} else {
return s === m;
}
}
function match2(b: Pos, q: Matcher<Pos>): boolean {
return match(b[0], q[0]) && match(b[1], q[1]);
}
const poss: Pos[] = [[1, 1], [1, 2], [2, 1]]
let res = poss.filter(_ => match2(_, [1, "*"])) // [[1, 1], [1, 2]]
console.log(res);
The reference equality between item properties and query literals is causing the error.
Edit
The previous solution fixed my initial problem. Now, I want to implement nested queries like the ones shown below:
interface Pos2 {
file: string,
rank: string
}
interface Board {
p1: Pos2,
p2: Pos2
}
function match3<A>(b: A, q: MapMatcher<A>): boolean {
if (typeof b === 'object' && typeof q === 'object') {
for (let key in b) {
if (!match(q[key], b[key])) {
return false;
}
}
return true;
} else {
return false;
}
}
let a2 = {
file: "a",
rank: "2"
}, a3 = {
file: "a",
rank: "3"
}, b1 = {
file: "b",
rank: "1"
}, b2 = {
file: "b",
rank: "2"
};
let poss2 = [a2,a3,b1,b2]
let boards = [{
p1: a2,
p2: a3
}, {
p1: a2,
p2: b1
}, {
p1: a3,
p2: b2
}]
function query<A>(arr: A[], m: MapMatcher<A>): A[] {
return arr.filter(_ => match3(_, m));
}
let q1 = query(poss2, {
file: "a",
rank: "*"
})
// nested equality
query(boards, {
p1: q1,
p2: "*"
});
// reference equality
match3(boards, {
p1: a2,
p2: "*"
})
The code above does not pass the compiler's checks.