knadh / localStorageDB

A simple database layer for localStorage and sessionStorage for creating structured data in the form of databases and tables
http://nadh.in/code/localstoragedb
814 stars 128 forks source link

sort:[[]] always sorts by ID and Ascending order #40

Closed fikrifirat closed 10 years ago

fikrifirat commented 10 years ago

Hi all,

It seems to sort only by ID, no matter what you enter in the sort field. The following is the query format I used : lib.queryAll("SearchHistory", { limit: limit, sort: [["viewCount", "DESC"]]});

viewCount is an integer value, I also tested with string values.

Any ideas? Is there something I'm doing wrong?

I tested in the Chrome Developer Console, web page running on iPhone, iPad, BlackBerry Q10 and Windows desktop clients.

knadh commented 10 years ago

@fikrifirat, I am unable to reproduce the issue (Firefox, Chrome). I tested with the books sample.

console.log( lib.queryAll("books", { limit: 5, sort: [["title", "DESC"]]}) );

fikrifirat commented 10 years ago

@knadh Sorry, there was a different problem with desktop clients. It works on desktop but NOT on mobile devices. Can you also check?

pianomister commented 10 years ago

I experienced the same problem in Safari on desktop and on iOS. This is caused by the comparison function (line 196 and 198) which is returning true or false:

if(order === "DESC") {
    return v1 < v2;
} else {
    return v1 > v2;
}

According to specification, the function expects a positive, zero or negative value. Also see here: http://stackoverflow.com/questions/4299062/why-wont-safari-5-sort-an-array-of-objects

if(order === "DESC") {
    return ((v1 < v2) ? 1 : -1);
} else {
    return ((v1 > v2) ? 1 : -1);
}

This fixed the problem for me, sorting works now in Safari 5.1.7 (Windows 7) and in Safari Mobile (iOS7). Zero value is not considered here, maybe you find a better fix. Would be nice if you include this into the build!

knadh commented 10 years ago

Thanks for potinging out! https://github.com/knadh/localStorageDB/commit/429a8fdb8da16053826825fa4dee3f269911f1fc fixes the issue (and considers 0)