Repos
C++
1.3 KB37 lines Opens in site
Directory
Raw
Download
#include "model/Reactions.hpp"
#include <algorithm>
#include "core/JsonDecode.hpp"
namespace dp {
Reactions Reactions::fromJson(const Json& j) {
using D = JsonDecode;
Reactions r;
r.mine = D::reqList<std::string>(j, "mine", [](const Json& v) { return D::convert<std::string>(v, "mine"); });
const Json& counts = D::child(j, "counts");
if (!counts.is_object()) throw DecodeError("counts is not an object");
if (counts.size() > spec::ModelLimits::kMaxListItems) throw DecodeError("counts too large");
for (auto it = counts.begin(); it != counts.end(); ++it) r.counts[it.key()] = D::convert<std::int64_t>(it.value(), "counts");
return r;
}
Reactions Reactions::toggling(const std::string& emoji) const {
Reactions out = *this;
const bool has = std::find(mine.begin(), mine.end(), emoji) != mine.end();
if (has) {
auto it = out.counts.find(emoji);
const std::int64_t next = (it == out.counts.end() ? 1 : it->second) - 1;
if (next > 0) out.counts[emoji] = next;
else out.counts.erase(emoji);
out.mine.erase(std::remove(out.mine.begin(), out.mine.end(), emoji), out.mine.end());
} else {
auto it = out.counts.find(emoji);
out.counts[emoji] = (it == out.counts.end() ? 0 : it->second) + 1;
out.mine.push_back(emoji);
}
return out;
}
} // namespace dp