DEV Community

Francisco Zanfranceschi
Francisco Zanfranceschi

Posted on

1

[Desafio] - Agregação de Registros

Conteúdo original em https://twitter.com/zanfranceschi/status/1679497149732585472


Ei dev,

Pega esse desafio de agregação de registros!

Dado registros granulares que contêm data e quantidade, crie uma função que os agregue por data em um dicionário e some os atributos "qtd". O código a seguir explica melhor o desafio.

# dado os seguintes registros
registros = [{"data" : "2023-07-13", "qtd" : 12},
             {"data" : "2023-07-14", "qtd" : 30},
             {"data" : "2023-07-13", "qtd" : 4},
             {"data" : "2023-07-14", "qtd" : 98},
             {"data" : "2023-07-12", "qtd" : 4},
             {"data" : "2023-07-12", "qtd" : 8},
             {"data" : "2023-07-12", "qtd" : 31},
             {"data" : "2023-07-15", "qtd" : 74},
             {"data" : "2023-07-13", "qtd" : 12},
             {"data" : "2023-07-12", "qtd" : 1},
             {"data" : "2023-07-17", "qtd" : 3},
             {"data" : "2023-07-16", "qtd" : 35}]

# desenvolva uma função de agrupamento
resultado = agrupar(registros)

# que retorne o seguinte resultado
{"2023-07-13" : 28,
 "2023-07-14" : 128,
 "2023-07-12" : 44,
 "2023-07-15" : 74,
 "2023-07-17" : 3,
 "2023-07-16" : 35}`
Enter fullscreen mode Exit fullscreen mode

Se alguém tiver curiosidade sobre como isso poderia ser feito em Clojure, aí está.

(defn agrupar
  [registros]
  (into {} (map (fn [i]
                  [(first i)
                   (->> (map :qtd (second i))
                        (reduce +))])
                (group-by :data registros))))

(agrupar [{:data "2023-07-13", :qtd 12}
          {:data "2023-07-14", :qtd 30}
          {:data "2023-07-13", :qtd 4}
          {:data "2023-07-14", :qtd 98}
          {:data "2023-07-12", :qtd 4}
          {:data "2023-07-12", :qtd 8}
          {:data "2023-07-12", :qtd 31}
          {:data "2023-07-15", :qtd 74}
          {:data "2023-07-13", :qtd 12}
          {:data "2023-07-12", :qtd 1}
          {:data "2023-07-17", :qtd 3}
          {:data "2023-07-16", :qtd 35}])
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay