From c32d8a5db030168b042ad52b2a6dd99bb34d4d87 Mon Sep 17 00:00:00 2001 From: Solderpunk Date: Tue, 5 Nov 2019 20:30:09 +0000 Subject: Factor out duplicated code between do_recent and do_search. --- telem.lua | 67 +++++++++++++++++++++++++-------------------------------------- 1 file changed, 27 insertions(+), 40 deletions(-) diff --git a/telem.lua b/telem.lua index a087954..3c6ac8e 100755 --- a/telem.lua +++ b/telem.lua @@ -471,24 +471,7 @@ function do_new() end function do_recent() - local recent = {} - local N = 10 - for i, board in ipairs(boards) do - local threads = get_threads(board) - for _, thread in ipairs(threads) do - local x = {} - x.board = board - x.thread = thread - if #recent < N then - table.insert(recent, x) - table.sort(recent, function(x,y) return x.thread.updated > y.thread.updated end) - elseif thread.updated > recent[N].thread.updated then - table.remove(recent, N) - table.insert(recent, x) - table.sort(recent, function(x,y) return x.thread.updated > y.thread.updated end) - end - end - end + local recent = filter_latest_posts(function(x) return true end, 10) print("Most recently active threads:") print(colourise("magenta", string.format("%s %s %s", stringx.ljust("Board name", 20), @@ -504,6 +487,29 @@ function do_recent() print(string.rep("-",79)) end +function filter_latest_posts(filter, N) + local matches = {} + for i, board in ipairs(boards) do + local threads = get_threads(board) + for _, thread in ipairs(threads) do + local x = {} + x.board = board + x.thread = thread + if filter(x) == nil then + -- pass + elseif #matches < N then + table.insert(matches, x) + table.sort(matches, function(x,y) return x.thread.updated > y.thread.updated end) + elseif thread.updated > matches[N].thread.updated then + table.remove(matches, N) + table.insert(matches, x) + table.sort(matches, function(x,y) return x.thread.updated > y.thread.updated end) + end + end + end + return matches +end + function do_scan() for i, board in ipairs(boards) do io.write(string.format("%3d ", i)) @@ -531,28 +537,9 @@ function do_search() print("Search cancelled.") return end - local hits = {} - local N = 10 - for i, board in ipairs(boards) do - local threads = get_threads(board) - for _, thread in ipairs(threads) do - local x = {} - x.board = board - x.thread = thread - if string.find(string.lower(x.thread.subject), string.lower(searchterm)) == nil then - goto continue - end - if #hits < N then - table.insert(hits, x) - table.sort(hits, function(x,y) return x.thread.updated > y.thread.updated end) - elseif thread.updated > hits[N].thread.updated then - table.remove(hits, N) - table.insert(hits, x) - table.sort(hits, function(x,y) return x.thread.updated > y.thread.updated end) - end - ::continue:: - end - end + local hits = filter_latest_posts(function(x) + return string.find(string.lower(x.thread.subject), string.lower(searchterm)) + end, 10) if #hits == 0 then print("No hits found.") return -- cgit v1.2.3