fork download
  1.  
  2. public with sharing class BooleanEvaluate {
  3.  
  4. private static final String ANDv = 'AND';
  5. private static final String ORv = 'OR';
  6. private static final String OPEN = '(';
  7. private static final String CLOSE = ')';
  8.  
  9. /**
  10. * @description Evaluates a boolean expression to a boolean result
  11. * @param expression Expression [eg. `1 || ( 2 && 3 )` ]
  12. * @param values List of boolean values to be evaluated with the expression
  13. * @return final boolean evaluation
  14. */
  15. public static Boolean evaluate(String expression, Boolean[] values){
  16. expression = expression.replaceAll('\\|\\|', 'OR').replaceAll('&&', 'AND');
  17. expression = formatExpression(expression, values);
  18.  
  19. if(!expression.contains(OPEN)){
  20. return evaluateExpression(expression);
  21. }
  22.  
  23. Integer indexOfOpen = -1;
  24. Integer indexOfClose = -1;
  25.  
  26. String[] chars = expression.split('');
  27. for(Integer i = 0; i < chars.size(); i++){
  28.  
  29. String singleChar = chars[i];
  30.  
  31. if(singleChar == OPEN) {
  32. indexOfOpen = i;
  33. continue;
  34. }
  35.  
  36. if(singleChar == CLOSE) {
  37. indexOfClose = i;
  38. break;
  39. }
  40. }
  41.  
  42. String replace = expression.substring(indexOfOpen + 1 , indexOfClose);
  43. expression = expression.replace( OPEN + replace + CLOSE, String.valueOf( evaluateExpression(replace) ) );
  44. return evaluate(expression, values);
  45. }
  46.  
  47. private static Boolean evaluateExpression(String expression){
  48.  
  49. Boolean result = false;
  50. for( String conj : expression.split(ORv) ){
  51.  
  52. Boolean b = true;
  53. for( String single : conj.split(ANDv) ){
  54. b &= Boolean.valueOf(single.trim());
  55. }
  56.  
  57. result |= b;
  58. }
  59.  
  60. return result;
  61.  
  62. }
  63.  
  64. private static String formatExpression(String originalExpression, Boolean[] values){
  65.  
  66. String formattedExpression = originalExpression;
  67. String[] arguments = formattedExpression.split(' ');
  68. for(String arg : arguments){
  69. try{
  70. Integer index = Integer.valueOf(arg);
  71. formattedExpression = formattedExpression.replace(arg, String.valueOf(values[index - 1]));
  72. }catch(Exception e){
  73. continue;
  74. }
  75. }
  76. return formattedExpression;
  77. }
  78. }
Success #stdin #stdout #stderr 0.01s 9056KB
stdin
Standard input is empty
stdout
Object: nil error: did not understand #with
MessageNotUnderstood(Exception)>>signal (ExcHandling.st:254)
UndefinedObject(Object)>>doesNotUnderstand: #with (SysExcept.st:1448)
UndefinedObject>>executeStatements (prog:2)
stderr
./prog:5: parse error, expected '}'
./prog:11: Invalid character `
./prog:11: Invalid character `
./prog:19: expected expression