From 13d1f6d6c1935f73ea833ebbeb81094542240bb5 Mon Sep 17 00:00:00 2001 From: "jeremy@jermolene.com" Date: Tue, 4 Jan 2022 09:59:23 +0000 Subject: [PATCH] Less naive fix Now we make sure we maintain the sort order of the titles array when adding a new tiddler --- boot/boot.js | 26 ++++++++++++++++++---- editions/test/tiddlers/tests/test-utils.js | 10 +++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/boot/boot.js b/boot/boot.js index 8b3a9c509..6b8c50255 100644 --- a/boot/boot.js +++ b/boot/boot.js @@ -68,6 +68,26 @@ $tw.utils.isArrayEqual = function(array1,array2) { }); }; +/* +Add an entry to a sorted array if it doesn't already exist, while maintaining the sort order +*/ +$tw.utils.insertSortedArray = function(array,value) { + var low = 0, high = array.length - 1, mid, cmp; + while(low <= high) { + mid = (low + high) >> 1; + cmp = array[mid]; + if(value > cmp) { + low = mid + 1; + } else if(value < cmp) { + high = mid - 1; + } else { + return array; + } + } + array.splice(low,0,value); + return array; +}; + /* Push entries onto an array, removing them first if they already exist in the array array: array to modify (assumed to be free of duplicates) @@ -1134,10 +1154,8 @@ $tw.Wiki = function(options) { } // Save the new tiddler tiddlers[title] = tiddler; - // Check we've got it's title - if(tiddlerTitles && tiddlerTitles.indexOf(title) === -1) { - tiddlerTitles.push(title); - } + // Check we've got the title + tiddlerTitles = $tw.utils.insertSortedArray(tiddlerTitles || [],title); // Record the new tiddler state updateDescriptor["new"] = { tiddler: tiddler, diff --git a/editions/test/tiddlers/tests/test-utils.js b/editions/test/tiddlers/tests/test-utils.js index e8f4de32f..33530351f 100644 --- a/editions/test/tiddlers/tests/test-utils.js +++ b/editions/test/tiddlers/tests/test-utils.js @@ -169,6 +169,16 @@ describe("Utility tests", function() { expect(cv("1.1.1","1.1.2")).toEqual(-1); }); + it("should insert strings into sorted arrays", function() { + expect($tw.utils.insertSortedArray([],"a").join(",")).toEqual("a"); + expect($tw.utils.insertSortedArray(["b","c","d"],"a").join(",")).toEqual("a,b,c,d"); + expect($tw.utils.insertSortedArray(["b","c","d"],"d").join(",")).toEqual("b,c,d"); + expect($tw.utils.insertSortedArray(["b","c","d"],"f").join(",")).toEqual("b,c,d,f"); + expect($tw.utils.insertSortedArray(["b","c","d","e"],"f").join(",")).toEqual("b,c,d,e,f"); + expect($tw.utils.insertSortedArray(["b","c","g"],"f").join(",")).toEqual("b,c,f,g"); + expect($tw.utils.insertSortedArray(["b","c","d"],"ccc").join(",")).toEqual("b,c,ccc,d"); + }); + }); })();