All files / metadata/src/safeFunctions matchTests.ts

39.09% Statements 43/110
30.13% Branches 22/73
18.96% Functions 11/58
43.75% Lines 42/96

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348                                                                                    137x 4110x       137x 137x   137x       137x             137x     137x         137x                         137x 137x                       2740x 2740x                                                               2740x 2740x 2740x             548x                   137x 548x               548x 548x     137x 137x 137x 137x             137x                               137x                         274x   274x                                                                                                                                                                                                               3151x     3151x     3151x     2466x   685x 274x                 274x   411x             411x 411x 411x 411x             411x    
/**
 * The **tests** of a condition map: what one entry `name: test` checks on the
 * value of the name.
 *
 * | Test                     | The entry holds when                                     |
 * | ------------------------ | -------------------------------------------------------- |
 * | a scalar                 | shorthand for `includes`: the value is or holds the scalar |
 * | an array of scalars      | shorthand for `includes`: one value is in the array       |
 * | `null`                   | the value has no value: absent or empty                  |
 * | an object, one operator  | the operator holds (see {@link MATCH_OPERATORS})          |
 * | a function               | `test(value, subject, context)` is true                  |
 *
 * The operators have the names of the OHIF hanging protocol constraints.
 * Use `equals` for a whole-value test. `equals` compares the whole value: an array operand equals an array value
 * element by element. `notNull` is the opposite of `null`, `includes` accepts
 * a scalar operand. `greaterThan` / `lessThan` are strict, and
 * `greaterThanOrEqual` / `lessThanOrEqual` include the limit; the four read a
 * numeric string or the first element of an array as a number. A test on no
 * value fails, and the `does...Not` form holds.
 *
 * @module safeFunctions/matchTests
 */
 
import { asArray, toFiniteFirst } from '@cornerstonejs/utils';
import { compareFinite, hasNoValue, looseEquals } from './values';
import { invalidAt, matchForm, matchTestShape } from './schema';
import type { SchemaSite } from './schema';
 
/** A compiled test of one value. */
export type ValueTest = (
  value: unknown,
  subject?: unknown,
  context?: unknown
) => boolean;
 
type Operator = {
  /** What the operand must be, for the error message. */
  readonly operand: string;
  readonly accepts: (operand: unknown) => boolean;
  readonly compile: (operand: unknown) => ValueTest;
};
 
const isScalar = (value: unknown): boolean =>
  typeof value === 'string' ||
  typeof value === 'boolean' ||
  (typeof value === 'number' && Number.isFinite(value));
 
const isFiniteNumber = (value: unknown): value is number =>
  typeof value === 'number' && Number.isFinite(value);
 
const isScalarOrScalars = (value: unknown): boolean =>
  isScalar(value) ||
  (Array.isArray(value) && value.length > 0 && value.every(isScalar));
 
const isTextOrTexts = (value: unknown): boolean =>
  typeof value === 'string' ||
  (Array.isArray(value) &&
    value.length > 0 &&
    value.every((item) => typeof item === 'string'));
 
/** The elements of a value: a single value is a one-element array. */
const elementsOf = (value: unknown): unknown[] =>
  hasNoValue(value) ? [] : asArray(value).filter((item) => !hasNoValue(item));
 
const textsOf = (value: unknown, ignoreCase = false): string[] =>
  elementsOf(value).map((item) =>
    ignoreCase ? String(item).toLowerCase() : String(item)
  );
 
const needlesOf = (operand: unknown, ignoreCase = false): string[] =>
  asArray(operand).map((item) =>
    ignoreCase ? String(item).toLowerCase() : String(item)
  );
 
/** `equals`: the whole value with `==`, and `null` for "no value". */
function equalsTest(operand: unknown): ValueTest {
  return operand === null
    ? (value) => hasNoValue(value)
    : (value) => looseEquals(value, operand);
}
 
/** A list of at most this many elements keeps the loop. */
const SET_MIN_LENGTH = 9;
const stringSets = new WeakMap<
  readonly unknown[],
  ReadonlySet<string> | null
>();
 
/**
 * The cached `Set` of a stable array of more than 8 non-empty strings, else
 * `null`. The array is the key, so it must not change after the compile. The
 * compile holds its own copy of each array of a rule and of the context, and
 * folds an array literal of literals into one array.
 */
function stringSetOf(list: unknown): ReadonlySet<string> | null {
  Eif (!Array.isArray(list) || list.length < SET_MIN_LENGTH) {
    return null;
  }
  let set = stringSets.get(list);
  if (set === undefined) {
    set = list.every((element) => typeof element === 'string' && element)
      ? new Set(list as string[])
      : null;
    stringSets.set(list, set);
  }
  return set;
}
 
/**
 * True when one of `items` equals an element of `list` with
 * {@link looseEquals}. `list` is the stable side of the membership test.
 *
 * With a `Set` of `list`, a string and a boolean (as `'true'` / `'false'`)
 * look up the `Set`. That gives the result of `looseEquals`, which compares two
 * non-empty texts as `String(a) === String(b)`. A number, or an item of
 * another kind, keeps the loop, so `1` still equals `'1'` and `'01'`.
 */
function someInList(items: readonly unknown[], list: unknown): boolean {
  const set = stringSetOf(list);
  const elements = set ? (list as readonly unknown[]) : elementsOf(list);
  return items.some((item) =>
    set && (typeof item === 'string' || typeof item === 'boolean')
      ? set.has(String(item))
      : elements.some((element) => looseEquals(item, element))
  );
}
 
function includesTest(operand: unknown): ValueTest {
  const wanted = [...asArray(operand)];
  stringSetOf(wanted);
  return (value) => someInList(elementsOf(value), wanted);
}
 
function textTest(
  ignoreCase: boolean,
  test: (text: string, needle: string) => boolean
): (operand: unknown) => ValueTest {
  return (operand) => {
    const needles = needlesOf(operand, ignoreCase);
    return (value) =>
      textsOf(value, ignoreCase).some((text) =>
        needles.some((needle) => test(text, needle))
      );
  };
}
 
const not =
  (compile: (operand: unknown) => ValueTest) =>
  (operand: unknown): ValueTest => {
    const test = compile(operand);
    return (value, subject, context) => !test(value, subject, context);
  };
 
function numberTest(
  test: (value: number, operand: number) => boolean
): (operand: unknown) => ValueTest {
  const compare = compareFinite(test);
  return (operand) => (value) => compare(value, operand);
}
 
const contains = textTest(false, (text, needle) => text.includes(needle));
const containsI = textTest(true, (text, needle) => text.includes(needle));
const startsWith = textTest(false, (text, needle) => text.startsWith(needle));
const endsWith = textTest(false, (text, needle) => text.endsWith(needle));
 
/**
 * The operator meanings as functions of a value and an operand, for the
 * expression helpers of the same names. So `includes(ImageType, 'LOCALIZER')`
 * and `{ "includes": "LOCALIZER" }` give the same result.
 */
export const MATCH_HELPERS = Object.freeze({
  // The value is the stable side: `X in list` calls includes(list, X).
  includes: (value: unknown, operand: unknown) =>
    someInList(elementsOf(operand), value),
  contains: (value: unknown, operand: unknown) => contains(operand)(value),
  startsWith: (value: unknown, operand: unknown) => startsWith(operand)(value),
  endsWith: (value: unknown, operand: unknown) => endsWith(operand)(value),
});
 
/**
 * The operators of a test, by name: the operand each one accepts, and its
 * meaning. A test on no value fails, except for `doesNotEqual`,
 * `doesNotInclude`, `doesNotContain`, `doesNotContainI` and
 * `{ "notNull": false }`, which hold.
 */
export const MATCH_OPERATORS: Readonly<Record<string, Operator>> =
  Object.freeze({
    equals: {
      operand: 'a scalar, a non-empty array of scalars, or null',
      accepts: (operand) => operand === null || isScalarOrScalars(operand),
      compile: equalsTest,
    },
    doesNotEqual: {
      operand: 'a scalar, a non-empty array of scalars, or null',
      accepts: (operand) => operand === null || isScalarOrScalars(operand),
      compile: not(equalsTest),
    },
    notNull: {
      operand: 'a boolean',
      accepts: (operand) => typeof operand === 'boolean',
      compile: (operand) =>
        operand ? (value) => !hasNoValue(value) : (value) => hasNoValue(value),
    },
    includes: {
      operand: 'a scalar, or a non-empty array of scalars',
      accepts: isScalarOrScalars,
      compile: includesTest,
    },
    doesNotInclude: {
      operand: 'a scalar, or a non-empty array of scalars',
      accepts: isScalarOrScalars,
      compile: not(includesTest),
    },
    greaterThan: {
      operand: 'a finite number',
      accepts: isFiniteNumber,
      compile: numberTest((value, operand) => value > operand),
    },
    greaterThanOrEqual: {
      operand: 'a finite number',
      accepts: isFiniteNumber,
      compile: numberTest((value, operand) => value >= operand),
    },
    lessThan: {
      operand: 'a finite number',
      accepts: isFiniteNumber,
      compile: numberTest((value, operand) => value < operand),
    },
    lessThanOrEqual: {
      operand: 'a finite number',
      accepts: isFiniteNumber,
      compile: numberTest((value, operand) => value <= operand),
    },
    range: {
      operand: 'an array of two finite numbers',
      accepts: (operand) =>
        Array.isArray(operand) &&
        operand.length === 2 &&
        operand.every(isFiniteNumber),
      compile: (operand) => {
        const [a, b] = operand as number[];
        const low = Math.min(a, b);
        const high = Math.max(a, b);
        return (value) => {
          const number = toFiniteFirst(value);
          return number !== undefined && number >= low && number <= high;
        };
      },
    },
    contains: {
      operand: 'a string, or a non-empty array of strings',
      accepts: isTextOrTexts,
      compile: contains,
    },
    containsI: {
      operand: 'a string, or a non-empty array of strings',
      accepts: isTextOrTexts,
      compile: containsI,
    },
    doesNotContain: {
      operand: 'a string, or a non-empty array of strings',
      accepts: isTextOrTexts,
      compile: not(contains),
    },
    doesNotContainI: {
      operand: 'a string, or a non-empty array of strings',
      accepts: isTextOrTexts,
      compile: not(containsI),
    },
    containsAll: {
      operand: 'a scalar, or a non-empty array of scalars',
      accepts: isScalarOrScalars,
      compile: (operand) => {
        const wanted = asArray(operand);
        return (value) => {
          const elements = elementsOf(value);
          return (
            elements.length > 0 &&
            wanted.every((element) =>
              elements.some((item) => looseEquals(item, element))
            )
          );
        };
      },
    },
    startsWith: {
      operand: 'a string, or a non-empty array of strings',
      accepts: isTextOrTexts,
      compile: startsWith,
    },
    endsWith: {
      operand: 'a string, or a non-empty array of strings',
      accepts: isTextOrTexts,
      compile: endsWith,
    },
  });
 
/**
 * Compiles the test of one entry of a condition map. See the table of this
 * module for the forms.
 *
 * @throws when the test is not one of the forms, or an operand is not of the
 *   kind its operator accepts.
 */
export function compileMatchTest(test: unknown, site: SchemaSite): ValueTest {
  Iif (typeof test === 'function') {
    return test as ValueTest;
  }
  Iif (test === null) {
    return equalsTest(test);
  }
  if (isScalar(test)) {
    // The shorthand is `includes`: a single value equals the scalar, and a
    // multi-valued value holds it. `{ equals }` compares the whole value.
    return includesTest(test);
  }
  if (Array.isArray(test)) {
    Iif (!test.length || !test.every(isScalar)) {
      return invalidAt(
        site,
        'an array test must hold one or more scalars',
        test
      );
    }
    // Shorthand for `includes`: a single value is one of the elements, and a
    // multi-valued value has one element in common with the array.
    return includesTest(test);
  }
  Iif (!test || typeof test !== 'object') {
    return invalidAt(
      site,
      'expected a scalar, an array of scalars, null, an object with one operator, or a function',
      test
    );
  }
  matchForm(matchTestShape, test, site);
  const [name, operand] = Object.entries(test)[0];
  const operator = MATCH_OPERATORS[name];
  Iif (!operator.accepts(operand)) {
    return invalidAt(
      site,
      `the operand of ${name} must be ${operator.operand}`,
      test
    );
  }
  return operator.compile(operand);
}