All files / collections / includes_value.ts

100.00% Branches 6/6
100.00% Lines 13/13
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x3
x3
x3
 
x15
x27
x27
x27
x27
x32
x32
x27
 
x22
x15











































// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.

/**
 * Returns true if the given value is part of the given object, otherwise it
 * returns false.
 *
 * Note: this doesn't work with non-primitive values. For example,
 * `includesValue({x: {}}, {})` returns false.
 *
 * @typeParam T The type of the values in the input record.
 *
 * @param record The record to check for the given value.
 * @param value The value to check for in the record.
 *
 * @returns `true` if the value is part of the record, otherwise `false`.
 *
 * @example Basic usage
 * ```ts
 * import { includesValue } from "@std/collections/includes-value";
 * import { assertEquals } from "@std/assert";
 *
 * const input = {
 *   first: 33,
 *   second: 34,
 * };
 *
 * assertEquals(includesValue(input, 34), true);
 * ```
 */
export function includesValue<T>(
  record: Readonly<Record<string, T>>,
  value: T,
): boolean {
  for (const i in record) {
    if (
      Object.hasOwn(record, i) &&
      (record[i] === value || Number.isNaN(value) && Number.isNaN(record[i]))
    ) {
      return true;
    }
  }

  return false;
}