All files / src/utils coerceIntoClause.ts

77.27% Statements 17/22
66.67% Branches 6/9
75% Functions 3/4
77.27% Lines 17/22
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  15x 15x 15x 15x 15x 15x 15x 15x 15x 15x   27081x 24873x   2208x 2208x             15x   2208x                     2208x                        
import isPred from "./isPred";
import isClause from "./isClause";
import isClauseRef from "./isClauseRef";
import isDelayedClause from "./isDelayedClause";
import Clause from "../models/Clause";
import Problem from "../models/Problem";
import fnName from "./fnName";
import stringifyWithFnName from "./stringifyWithFnName";
 
const CLAUSE_TYPE_PRED = "PRED";
 
export default function coerceIntoClause( expr ) {
  if ( isClause( expr ) || isClauseRef( expr ) || isDelayedClause( expr ) ) {
    return expr;
  } else if ( isPred( expr ) ) {
    returEn _wrap( expr );
  } else {
    console.error( expr );
    throw new Error(
      `'Expression must either be a Clause object or a predication function that returns true or false. Given value: ${stringifyWithFnName( expr )}'` );
  }
}
 
function _wrap( pred ) {
  return new Clause( {
    type: CLAUSE_TYPE_PRED,
    exprs: [ pred ],
    opts: {
      predicate: pred,
    },
    conformFn: predConformer( pred ),
    generateFn: null,
  } );
}
 
function predConformer( pred ) {
  return function conformPred( x ) {
    if ( pred( x ) ) {
      return x;
    } else {
      return new Problem(
        x,
        pred,
        [],
        `Predicate ${fnName( pred )} returns false`
      );
    }
  }
}