I'm having trouble sorting a string in a priority queue method I'm using. Here's an example of the string keys that I'm sorting:
[ '.0', '.1', '.2', '.4', '.2.1', '.3', '.4.1', '.5', '.5.1.5' ]
The values are representation of hierarchy that need to be ordered from smallest to largest. The result I'm expecting is:
[ '.0', '.1', '.2.1', '.2, '.3', '.4', '.4.1', '.5', '.5.1.5' ]
The method I'm using to push into my queue runs at O(log n)
and looks like so:
queue.add = function(myval) {
// console.log(myval);
var i = this.size;
this.array[this.size++] = myval;
while ( i > 0) {
var p = (i - 1) >> 1;
var ap = this.array[p];
if(!this.compare(myval, ap )) break;
this.array[i] = ap;
i = p;
}
};
And my compare function is simply:
(a, b) => {
return a[0] < b[0];
}
I was considering using localeCompare but since I'm in Node it doesn't seem to be dependably for some reason. When I use:
(a, b) => {
return a[0].localeCompare(b[0]) > 0;
}
I get a compareLocal not defined error which might be related to something else.
My question is hence, how can I efficiently determine the string ordering in the manner I've outlined?