Sorting strings in reverse order with backbone.js

后端 未结 6 2015
南方客
南方客 2020-12-08 07:25

I\'m trying to sort a Backbone.js collection in reverse order. There are previous replies on how to do this with integers, but none with strings.

var Chapter         


        
6条回答
  •  臣服心动
    2020-12-08 07:37

    You could:

    • grab the char code for each character in the string,
    • subtract each value from 0xffff (the maximum return value of string.charCodeAt),
    • use String.fromCharCode to turn that back into string of "negated" characters

    and that will be your sorting key.

    chapters.comparator = function(chapter) {
        return String.fromCharCode.apply(String,
            _.map(chapter.get("title").split(""), function (c) {
                return 0xffff - c.charCodeAt();
            })
        );
    }
    

    And voila:

    > console.log(chapters.pluck('title'));
    ["The Middle", "The End", "The Beginning"]
    

    Note: if your comparison strings are long (as in 65 kb or more), you may run into trouble (see Matt's comment below). To avoid this, and speed up comparisons a bit, just use a shorter slice of your comparison string. (In the above example, you could go for chapter.get("title").slice(0, 100).split("") instead.) How long a slice you need will depend on your application.

提交回复
热议问题