4

We have three different web pages that contain grid which is for adding details of master entity.

Detail object can be expressed in javascript by

var detail = {
     Description: 'Detail',
     MinPercentage: 0,
     MaxPercentage: 20
}

Now, we want to validate these details before sending to server.

Validations

  • There must not be any intersection. i.e. detail('Detail1', 0, 20) and detail('Detail2', 15, 30) are not valid, because between 15 and 20 are in common.
  • Details hold values from given minimum value to given maximum value. i.e.detail('Detail1', 0, 20) and detail('Detail2', 20, 40) hold values from 0 to 40. If given minimum is 0 and given maximum is 40, they are valid.

Expectations from Function

  • Because I want to write a function to use in multiple places, that should be as generic as possible.

Then, I wrote a function named areIntervalsValid but I am not sure how to handle calls with wrong inputs, throw exceptions, return best structured result and also I am wondering what is the best way to perform validations.


// Returns array of detail object to test.
var getDetails = function () {
    var detail1 = { Description: 'Detail1', MinPercentage: 0, MaxPercentage: 20 }
    var detail2 = { Description: 'Detail2', MinPercentage: 40, MaxPercentage: 60 }
    var detail3 = { Description: 'Detail3', MinPercentage: 60, MaxPercentage: 72 }
    var detail4 = { Description: 'Detail4', MinPercentage: 72, MaxPercentage: 100 }
    var detail5 = { Description: 'Detail5', MinPercentage: 20, MaxPercentage: 40 }

    return new Array(detail1, detail2, detail3, detail4, detail5);
}

// Performs type checking, logical validation, and requirements validation.
var areIntervalsValid = function (items, min, max, minProperty, maxProperty) {
    // Returned object.
    var result = {
        Success: false,
        Message: ''
    }

    // Checks arguments have expected types.
    var validateFunctionCall = function () {
        if (!Array.isArray(items) || typeof min !== 'number' || typeof max !== 'number' || typeof minProperty !== 'string' || typeof maxProperty !== 'string')
            throw 'An error occurred while processing validation.';
        if (!items.length || min > max)
            throw 'An error occurred while processing validation.';
    }

    // Checks [minProperty] of detail that has minimum [minProperty] == min
    // and [maxProperty] of detail that has maximum [minProperty]
    var validateIntervalBasics = function () {
        if (items[0][minProperty] != min || items[items.length - 1][maxProperty] != max)
            throw 'Start and end values of interval do not match minimum - maximum values.';
    }

    // Checks @item has [minProperty] and [maxProperty].
    var validateHasProperty = function (item) {
        if (!item.hasOwnProperty(minProperty) || !item.hasOwnProperty(maxProperty)) {
            throw 'An error occurred while processing validation.';
        }
    }

    try {
        validateFunctionCall();

        // Sorts array of details in according to [minProperty].
        items.sort(function (item1, item2) { return item1[minProperty] > item2[minProperty] });

        validateIntervalBasics();

        var totalDiff = 0, currentItem;

        // Algorithm part. 
        for (var i = 0; i < items.length; i++) {
            currentItem = items[i];
            validateHasProperty(currentItem);
            totalDiff += currentItem[maxProperty] - currentItem[minProperty];
            if (i != items.length - 1 && currentItem[maxProperty] > items[i + 1][minProperty]) { // Finds intersections.
                throw "There are intersected values: " + currentItem[maxProperty] + " - " + items[i + 1][minProperty];
            }
        }

        // Checks second validation.
        if (totalDiff != max - min) {
            throw 'Total interval sum is not equal to ' + (max - min);
        }

        result.Success = true;

        return result;

    } catch (e) {
        console.log(e);
        result.Message = e;

        return result;
    }
}

Then, I call the function like that:

areIntervalsValid(getDetails(), 0, 100, "MinPercentage", "MaxPercentage");

What can I do to the function to be more reliable, generic, and fast?

5
  • Is this code currently working as intended, and you just want to improve it? Jul 1, 2015 at 11:50
  • Are maximum and minimum inclusive or exclusive ? If you get Detail1(0, 50) and Detail2(50, 100), that means 49.99999 is part of Detail1 and 50.00001 is part of Detail2, but what about 50 ? Jul 1, 2015 at 11:58
  • @SebastienC. minimum is inclusive, maximum is exlusive.
    – dewe
    Jul 1, 2015 at 12:00
  • @SuperBiasedMan yeah it works. Because the question is not all about algorithm but also javascript, I wrote that down here.
    – dewe
    Jul 1, 2015 at 12:01
  • @dewe CodeReview might be better suited for this, they offer critique and suggestions to improve code that's already working. I might be misunderstanding your question though, so please read their site tour before asking there. Jul 1, 2015 at 12:03

1 Answer 1

1

This can be accomplished in nicer way if you use functional programming principles - recursion especially.

There is my solution for this problem. There is no data type validation logic because I believe you can do it yourself:

// Numbers and intervals comparison logic
function intervalsIntersect(start1, end1, start2, end2) {
  return inBetween(start1, start2, end2) || inBetween(end1, start2, end2);
}

function inBetween(value, start, end){
  return Math.max.apply(null, arguments) != value && Math.min.apply(null, arguments) != value;
}

// Validation logic
function getDetailsIntersectionReport(interval1, interval2) {
  var comparisonResult = intervalsIntersect(interval1.MinPercentage, interval1.MaxPercentage, interval2.MinPercentage, interval2.MaxPercentage);
  return comparisonResult ? ('[' + interval1.Description + ' instersects with ' + interval2.Description + '], ') : '';
}

function compareHeadWithTailFunctionFactory(head, comparatorFunction) {
  return function ( previous, item) {
    return previous + comparatorFunction(head, item);
  }
}

// you have to inject custom comparator function to make this function generic
function validateWithReport(list, comparatorFunction) {
  if (list.length <= 1) { // return if there is nothing to compare
    return '';
  }
  var head = list[0];
  var tail = list.slice(1);
  return tail.reduce(compareHeadWithTailFunctionFactory(head, comparatorFunction), 
  '' // initial value - empty string
  ) + validateWithReport(tail, comparatorFunction);

}

function validateIntervals(intervals) {
  var result = validateWithReport(intervals, getDetailsIntersectionReport);
  if (result.length) {
    throw new Error('There are intersecting intervals: ' + result);
  }
  return true;
}

// Unit test with Jasmine
describe('validation with report', function() {
  
  var intervalsWithoutIntersections = [
    { Description: 'Detail1', MinPercentage: 0, MaxPercentage: 20 },
    { Description: 'Detail2', MinPercentage: 40, MaxPercentage: 60 },
    { Description: 'Detail3', MinPercentage: 60, MaxPercentage: 72 }
  ];

  var intervalsWithIntersections = [
    { Description: 'Detail4', MinPercentage: 0, MaxPercentage: 21 },
    { Description: 'Detail5', MinPercentage: 20, MaxPercentage: 60 },
    { Description: 'Detail6', MinPercentage: 60, MaxPercentage: 72 }
  ];  
  
  it('should report with exception about error', function() {
    expect( function() { // wrapping into closure to catch error properly
      validateIntervals(intervalsWithIntersections)
    }).toThrowError();
  });

  it('should report validation with true', function() {
    expect(validateIntervals(intervalsWithoutIntersections)).toBeTruthy();
  });

});

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.