The best way to check the length of a string

advertisements

I'm coding a small web app, in which a user will have a row of n elements, and he's required to toggle each element to true/false, according to his own criteria.

Each time the user toggles an element, I have to check the length of the 'chain' of true elements the toggled element might be part of. examples:

0 0 0 0 1 0 1 1 1 ? //if user selects '1', the chain length is 4
0 ? 1 1 0 1 1 0 0 0 //if user selects '1', the chain length is 3
0 0 1 1 1 ? 1 1 0 0 //if user selects '1', the chain length is 6

I'm thinking about the best way of doing this.

All elements will have representation both in a JSON object and as DOM objects (for example <div>s).

one option is to simply run through the entire array with every click. This is ok, as the maximum amount of elements will be about 1000. But it doesn't seem to be the most efficient way.

another option is to take the clicked element and step backwards while counting each additional true element, until reaching a false element. then doing the same from the clicked element onwards. This seems better to me but maybe it's an unnecessary hassle.

I need help deciding which method is most suitable for this problem. Factors are (not surprisingly) -

  1. Performance - it mustn't cause any lags on the client-side - the chain length must be determined instantly.
  2. Maintainability.

I realise this question might seem a bit subjective, and maybe it is, but I figured this must be a familiar problem with a familiar solution that I'm not aware of.

I'll be using jQuery.


I would find the longest chain first. This will require iterating through your elements once.

After that, radiate outwards from the position of each changed element and find the longest chain.

$('.box').click(function() {
    $('.selected').removeClass('selected');

    var $this = $(this);
    $this.toggleClass('active');

    var $next = $this.nextUntil(':not(.active)');
    var $prev = $this.prevUntil(':not(.active)');

    if ($this.hasClass('active')) {
        var $chain = $next.add($prev).add($this);
    } else {
        var $chain = $next.length > $prev.length ? $next : $prev;
    }

    $chain.addClass('selected');
});

If that chain is longer than the longest chain, you found your new longest chain.

Demo: http://jsfiddle.net/EDVvN/4/