Skip to content

Commit

Permalink
Extract sort array function
Browse files Browse the repository at this point in the history
  • Loading branch information
nanaya committed Nov 17, 2024
1 parent d45aedd commit bfe4de7
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 21 deletions.
3 changes: 2 additions & 1 deletion app/javascript/src/classes/thumbnail_view.coffee
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { sortArrayByDistance } from '../utils/array'
import PreloadContainer from './preload_container'

# Handle the thumbnail view, and navigation for the main view.
Expand Down Expand Up @@ -161,7 +162,7 @@ export default class ThumbnailView
# centered on. If that doesn't match, move outwards from there. Only look forward
# a little bit, or we may match a post that was never seen and jump forward too far
# in the results.
post_id_search_order = sort_array_by_distance(old_post_ids.slice(0, old_centered_post_idx + 3), old_centered_post_idx)
post_id_search_order = sortArrayByDistance(old_post_ids.slice(0, old_centered_post_idx + 3), old_centered_post_idx)
initial_post_id = null
i = 0
while i < post_id_search_order.length
Expand Down
46 changes: 26 additions & 20 deletions app/javascript/src/utils/array.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,27 @@
###
# Return the values of list starting at idx and moving outwards.
#
# sort_array_by_distance([0,1,2,3,4,5,6,7,8,9], 5)
# [5,4,6,3,7,2,8,1,9,0]
###
/**
* Return the values of list starting at idx and moving outwards.
*
* sort_array_by_distance([0,1,2,3,4,5,6,7,8,9], 5)
* [5,4,6,3,7,2,8,1,9,0]
*/
export function sortArrayByDistance (list, idx) {
const ret = [list[idx]];

window.sort_array_by_distance = (list, idx) ->
ret = []
ret.push list[idx]
distance = 1
loop
length = ret.length
if idx - distance >= 0
ret.push list[idx - distance]
if idx + distance < list.length
ret.push list[idx + distance]
if length == ret.length
break
++distance
ret
for (let distance = 1; ; ++distance) {
const length = ret.length;

if (idx - distance >= 0) {
ret.push(list[idx - distance]);
}

if (idx + distance < list.length) {
ret.push(list[idx + distance]);
}

if (length === ret.length) {
break;
}
}

return ret;
}

0 comments on commit bfe4de7

Please sign in to comment.