How can I create a jQuery function that compresses a string using a binary search method?

I am trying to create a jQuery function that will take a string and a fixed width as input, and then through a binary search method (for efficiency) "compresses" this piece of text so that it does not exceed a fixed width.

This is what I have so far:

function constrain(text, ideal_width){
    var temp = $('.temp_item');
    temp.html(text);
    var item_width = temp.width();
    var ideal = parseInt(ideal_width);

    var text_len_lower = 0;
    var smaller_text = text;
    var text_len_higher = text.length;

    while (true) {
        if (item_width > ideal) {

            // make smaller to the mean of "lower" and this
            text_len_higher = smaller_text.length;
            smaller_text = text.substr(0, ((text_len_higher + text_len_lower)/2));

        } else {

            if (smaller_text.length >= text_len_higher) break;

            // make larger to the mean of "higher" and this
            text_len_lower = smaller_text.length;
            smaller_text = text.substr(0, ((smaller_text.length + text_len_higher)/2));

        }

        temp.html(smaller_text);
        item_width = temp.width();
    }

    var new_text = smaller_text + '…'
    return new_text;
}

Unfortunately, this causes a "slow script" that never terminates in my browser. Firebug points to jquery.js line 1131 (version 1.3.2), which is the "unique" jQuery utility, as the culprit. However, I do not use the “unique” option.

What am I doing wrong here?

+3
source share
2

javascript , ? Firebug Firefox MSVS IE. , , , .

, : , , . :

  • , ( ) . , , .

  • , ( ), .

  • HTML-, , HTML-, .

+2

-, :

text-overflow:ellipsis CSS. , IE IE, jQuery Firefox. Google "text-overflow: firefox", .

0

Source: https://habr.com/ru/post/1709232/


All Articles