matchCondition function

bool matchCondition(
  1. Object? c,
  2. Map<String, Object?> ctx,
  3. Object? segments, [
  4. int depth = 0,
])

Whether one condition matches ctx (matchCondition of the TypeScript engine). May throw a JsTypeError for malformed configuration, as the TypeScript engine does.

Implementation

bool matchCondition(Object? c, Map<String, Object?> ctx, Object? segments, [int depth = 0]) {
  final op = jsGet(c, 'op');
  if (op == 'segment' || op == 'not_segment') {
    final value = jsGet(c, 'value');
    final seg = value is String ? jsOwn(segments, value) : undefined;
    var inSeg = false;
    if (!isUndefined(seg) && depth < 4) {
      final match = jsGet(seg, 'match');
      final conditions = jsGet(seg, 'conditions');
      inSeg = _matchAll(match, conditions, ctx, segments, depth + 1);
    }
    return op == 'segment' ? inSeg : !isUndefined(seg) && !inSeg;
  }
  final attribute = jsString(jsGet(c, 'attribute'));
  final actual = ctx.containsKey(attribute) ? ctx[attribute] : undefined;
  final value = jsGet(c, 'value');
  if (op is! String) return false;
  switch (op) {
    case 'exists':
      return !isNullish(actual);
    case 'not_exists':
      return isNullish(actual);
    case 'eq':
      return looseEq(actual, value);
    case 'neq':
      return !isUndefined(actual) && !looseEq(actual, value);
    case 'in':
      return value is List && value.any((v) => looseEq(actual, v));
    case 'not_in':
      return !isUndefined(actual) && value is List && !value.any((v) => looseEq(actual, v));
    case 'contains':
      return actual is String && value is String && actual.contains(value);
    case 'starts_with':
      return actual is String && value is String && actual.startsWith(value);
    case 'ends_with':
      return actual is String && value is String && actual.endsWith(value);
    case 'gt':
    case 'gte':
    case 'lt':
    case 'lte':
      final a = _num(actual);
      final b = _num(value);
      if (a == null || b == null) return false;
      return switch (op) { 'gt' => a > b, 'gte' => a >= b, 'lt' => a < b, _ => a <= b };
    default:
      return false;
  }
}