Skip to content

Commit

Permalink
InsertEventIntoDescendingList() helper.
Browse files Browse the repository at this point in the history
  • Loading branch information
fiatjaf committed Jul 4, 2023
1 parent 6b625f7 commit 16580f3
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,57 @@ func escapeString(dst []byte, s string) []byte {
dst = append(dst, '"')
return dst
}

func InsertEventIntoDescendingList(sortedArray []*Event, event *Event) []*Event {
size := len(sortedArray)
start := 0
end := size - 1
var mid int
position := start

if end < 0 {
return []*Event{event}
} else if event.CreatedAt < sortedArray[end].CreatedAt {
return append(sortedArray, event)
} else if event.CreatedAt > sortedArray[start].CreatedAt {
newArr := make([]*Event, size+1)
newArr[0] = event
copy(newArr[1:], sortedArray)
return newArr
} else if event.CreatedAt == sortedArray[start].CreatedAt {
position = start
} else {
for {
if end <= start+1 {
position = end
break
}
mid = int(start + (end-start)/2)
if sortedArray[mid].CreatedAt > event.CreatedAt {
start = mid
} else if sortedArray[mid].CreatedAt < event.CreatedAt {
end = mid
} else {
position = mid
break
}
}
}

if sortedArray[position].ID != event.ID {
if cap(sortedArray) > size {
newArr := sortedArray[0 : size+1]
copy(newArr[position+1:], sortedArray[position:])
newArr[position] = event
return newArr
} else {
newArr := make([]*Event, size+1, size+5)
copy(newArr[:position], sortedArray[:position])
copy(newArr[position+1:], sortedArray[position:])
newArr[position] = event
return newArr
}
}

return sortedArray
}

0 comments on commit 16580f3

Please sign in to comment.