From 03ff93bfc9846b443d1e45d2e976c2916dc128d4 Mon Sep 17 00:00:00 2001 From: Vishesh Handa Date: Fri, 20 Mar 2020 23:47:56 +0100 Subject: [PATCH] SortedNotesFolder: Add another test --- lib/core/sorted_notes_folder.dart | 35 +++++++++++++++++++++++++----- test/sorted_notes_folder_test.dart | 24 ++++++++++++++++++++ 2 files changed, 54 insertions(+), 5 deletions(-) diff --git a/lib/core/sorted_notes_folder.dart b/lib/core/sorted_notes_folder.dart index ffcd60dd..7197ffa4 100644 --- a/lib/core/sorted_notes_folder.dart +++ b/lib/core/sorted_notes_folder.dart @@ -1,3 +1,5 @@ +import 'dart:math'; + import 'package:fimber/fimber.dart'; import 'package:flutter/material.dart'; import 'package:gitjournal/core/sorting_mode.dart'; @@ -80,26 +82,49 @@ class SortedNotesFolder with NotesFolderNotifier implements NotesFolder { } int _insertInCorrectPos(Note note) { + if (_notes.isEmpty) { + _notes.add(note); + return 0; + } + var i = _getInsertPos(note, 0, _notes.length - 1); - _notes.insert(i, note); + if (i == _notes.length) { + _notes.add(note); + } else { + _notes.insert(i, note); + } return i; } int _getInsertPos(Note note, int low, int high) { - int mid; + assert(low <= high); + + int mid = high; + while (low <= high) { mid = low + ((high - low) ~/ 2); var r = _sortFunc(_notes[mid], note); if (r == 0) { - return mid; - } else if (r < 0) { + return low; + } + + if (low == high) { + if (r < 0) { + return low + 1; + } else { + return low; + } + } + + if (r < 0) { low = mid + 1; } else { - high = mid - 1; + high = max(low, mid - 1); } } + assert(false); return mid; } diff --git a/test/sorted_notes_folder_test.dart b/test/sorted_notes_folder_test.dart index ab9a4e3c..7eacc25d 100644 --- a/test/sorted_notes_folder_test.dart +++ b/test/sorted_notes_folder_test.dart @@ -91,5 +91,29 @@ void main() { expect(sf.notes[4].body, "1"); expect(sf.notes[5].body, "0"); }); + + test('If still sorted while loading the notes', () async { + var folder = NotesFolderFS(null, tempDir.path); + var sf = SortedNotesFolder( + folder: folder, + sortingMode: SortingMode.Modified, + ); + + await folder.loadRecursively(); + + expect(sf.hasNotes, true); + expect(sf.isEmpty, false); + expect(sf.name.startsWith("__sorted_folder_test__"), true); + expect(sf.subFolders.length, 0); + expect(sf.notes.length, 5); + + expect(sf.notes[0].body, "4"); + expect(sf.notes[1].body, "3"); + expect(sf.notes[2].body, "2"); + expect(sf.notes[3].body, "1"); + expect(sf.notes[4].body, "0"); + }); + + // FIXME: Test if adding a note to the end works }); }