Skip to content

Instantly share code, notes, and snippets.

@madmongo1
Created December 28, 2020 09:49
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 madmongo1/cf7da66725da0865adf023a1784f1f7d to your computer and use it in GitHub Desktop.
Save madmongo1/cf7da66725da0865adf023a1784f1f7d to your computer and use it in GitHub Desktop.
template<class F>
concept mutable_value_visitor =
requires(F f, value& v)
{
{ f(v) };
};
template < mutable_value_visitor Visitor >
void
enumerate(value &v, Visitor f)
{
switch (v.kind())
{
case kind::null:
case kind::bool_:
case kind::int64:
case kind::uint64:
case kind::double_:
case kind::string:
f(v);
break;
case kind::array:
for (auto &entry : v.as_array())
enumerate(entry, f);
break;
case kind::object:
for (auto &entry : v.as_object())
enumerate(entry.value(), f);
break;
}
}
void
rectify_floats(value &v, double precision = 9)
{
auto op = [precision](value &x) {
if (auto d = x.if_double())
{
auto scale = std::floor(std::log10(*d));
auto rounding = std::pow(10.0, scale - precision);
*d = std::round(*d / rounding) * rounding;
}
};
enumerate(v, op);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment