1
0
mirror of https://github.com/Jermolene/TiddlyWiki5 synced 2025-08-05 21:33:52 +00:00

Reduced indexOf calls in wiki.sortByList (#4275) (#4397)

Examined the tests in test-tag. They already cover all the use cases
I could think of.
This commit is contained in:
Cameron Fischer 2020-04-14 12:49:10 -04:00 committed by GitHub
parent 69c8058b72
commit 43fdb553b7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -580,7 +580,9 @@ Sorts an array of tiddler titles according to an ordered list
exports.sortByList = function(array,listTitle) { exports.sortByList = function(array,listTitle) {
var self = this, var self = this,
replacedTitles = Object.create(null); replacedTitles = Object.create(null);
function replaceItem(title) { // Given a title, this function will place it in the correct location
// within titles.
function moveItemInList(title) {
if(!$tw.utils.hop(replacedTitles, title)) { if(!$tw.utils.hop(replacedTitles, title)) {
replacedTitles[title] = true; replacedTitles[title] = true;
var newPos = -1, var newPos = -1,
@ -593,26 +595,37 @@ exports.sortByList = function(array,listTitle) {
} else if(afterTitle === "") { } else if(afterTitle === "") {
newPos = titles.length; newPos = titles.length;
} else if(beforeTitle) { } else if(beforeTitle) {
replaceItem(beforeTitle); // if this title is placed relative
// to another title, make sure that
// title is placed before we place
// this one.
moveItemInList(beforeTitle);
newPos = titles.indexOf(beforeTitle); newPos = titles.indexOf(beforeTitle);
} else if(afterTitle) { } else if(afterTitle) {
replaceItem(afterTitle); // Same deal
moveItemInList(afterTitle);
newPos = titles.indexOf(afterTitle); newPos = titles.indexOf(afterTitle);
if(newPos >= 0) { if(newPos >= 0) {
++newPos; ++newPos;
} }
} }
// We get the currPos //after// figuring out the newPos, because recursive replaceItem calls might alter title's currPos // If a new position is specified, let's move it
var currPos = titles.indexOf(title); if (newPos !== -1) {
if(newPos === -1) { // get its current Pos, and make sure
newPos = currPos; // sure that it's _actually_ in the list
} // and that it would _actually_ move
if(currPos >= 0 && newPos !== currPos) { // (#4275) We don't bother calling
titles.splice(currPos,1); // indexOf unless we have a new
if(newPos >= currPos) { // position to work with
newPos--; var currPos = titles.indexOf(title);
if(currPos >= 0 && newPos !== currPos) {
// move it!
titles.splice(currPos,1);
if(newPos >= currPos) {
newPos--;
}
titles.splice(newPos,0,title);
} }
titles.splice(newPos,0,title);
} }
} }
} }
@ -640,7 +653,7 @@ exports.sortByList = function(array,listTitle) {
var sortedTitles = titles.slice(0); var sortedTitles = titles.slice(0);
for(t=0; t<sortedTitles.length; t++) { for(t=0; t<sortedTitles.length; t++) {
title = sortedTitles[t]; title = sortedTitles[t];
replaceItem(title); moveItemInList(title);
} }
return titles; return titles;
} }