Skip to content

matches() function

주어진 패턴의 모든 속성과 일치하는지 확인하는 술어(predicate) 함수를 생성합니다.

중첩 객체와 배열에 대해 깊은 비교를 수행합니다. find, filter, some, every에서 콜백 함수를 객체 패턴으로 대체할 때 유용합니다.

Signature:

typescript
function matches<T>(pattern: Record<Key, any>): (input: T) => boolean;

Example

ts
const users = [
  { name: "John", age: 30, active: true },
  { name: "Jane", age: 25, active: false },
  { name: "Bob", age: 30, active: true },
];

// filter와 함께 사용
filter(matches({ age: 30, active: true }), users);
// [{ name: "John", age: 30, active: true }, { name: "Bob", age: 30, active: true }]

// find와 함께 사용
find(matches({ active: true }), users);
// { name: "John", age: 30, active: true }

// pipe와 함께 사용
pipe(users, filter(matches({ active: true })), toArray);
// [{ name: "John", age: 30, active: true }, { name: "Bob", age: 30, active: true }]

// 중첩 객체 매칭
const data = [
  { id: 1, user: { profile: { age: 30 } } },
  { id: 2, user: { profile: { age: 25 } } },
  { id: 3, user: { profile: { age: 30 } } },
];
filter(matches({ user: { profile: { age: 30 } } }), data);
// [{ id: 1, user: { profile: { age: 30 } } }, { id: 3, user: { profile: { age: 30 } } }]

// 배열 값 매칭
const items = [
  { id: 1, tags: ["a", "b"] },
  { id: 2, tags: ["c", "d"] },
  { id: 3, tags: ["a", "b"] },
];
filter(matches({ tags: ["a", "b"] }), items);
// [{ id: 1, tags: ["a", "b"] }, { id: 3, tags: ["a", "b"] }]

// null/undefined 입력에 대해 false 반환
const matcher = matches({ a: 1 });
matcher(null);      // false
//      ~~~~
//      Error: Argument of type null is not assignable to parameter
matcher(undefined); // false
//     ~~~~~~~~~~
//     Error: Argument of type 'undefined' is not assignable to parameter```

패턴의 Symbol 키는 런타임에서 무시됩니다. (문자열 (및 숫자 키) 속성만 열거됩니다.)

```ts
const sym = Symbol("id");
// matches({ [sym]: 123 });
//           ~~~~
//           Error: Type 'symbol' cannot be used as an index type.

// 런타임에서 우회할 경우, Symbol 키는 무시됩니다:
const pattern = { [sym]: 123 } as any;
matches(pattern)({}); // true — Symbol 키는 비교되지 않음

Open Source Code

Released under the Apache-2.0 License.