Skip to content

Instantly share code, notes, and snippets.

@joffilyfe
Created March 17, 2022 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joffilyfe/010459680475f9c512ba8be6fd0d0f04 to your computer and use it in GitHub Desktop.
Save joffilyfe/010459680475f9c512ba8be6fd0d0f04 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
require_relative 'counter'
module SmartParser
module Counters
# Count the most visited path
class MostVisitedCounter < Counter
# Parse the received line using the @line_regex and counts
# how many times the parsed `path` was received.
#
# @returns true - when the line was correctly parsed and counted
# @returns false - when the line does not matches with the line regex
def count(line)
match = @line_regex.match(line.strip)
return false if match.nil?
path = match[:path]
address = match[:address]
@container[path] ||= Hash.new(0)
@container[path][address] += 1
if @container[path].nil?
@container[path] = 1
else
@container[path] += 1
end
true
end
# Returns an Array ordered by the most accessed path to the least accessed one
#
# @returns Array
def to_a
# puts @container.each.sort_by { |_k, v| v.values.sum }.map { |k, v| [k, v.values.sum] }
# @container.each.sort_by { |_k, v| v.values.sum }.reverse.map { |k, v| [k, v.values.sum] }
@container.each.sort_by { |_k, v| v }.reverse.to_a
end
def description
'Most visited'
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment