feat: add calculator logic

This commit is contained in:
jfmcarreira committed 2024-03-12 22:45:49 +00:00
1 parent 4d4f05cb4d
commit 0631eaa5fc
10 files changed
+579 -17

No files matched your search

+299
View File
@@ -0,0 +1,299 @@
---
Checks: '*, -llvm-header-guard,-abseil-*,-android-*,-boost-*,-clang-analyzer-osx-*,-fuchsia-*,-objc-*,-zircon-*,-llvm-namespace-comment,-google-runtime-references,-cppcoreguidelines-pro-bounds-constant-array-index,-google-readability-todo,-cppcoreguidelines-pro-bounds-pointer-arithmetic,-llvmlibc-*,-altera-*,-readability-magic-numbers,-cppcoreguidelines-avoid-magic-numbers,-bugprone-unchecked-optional-access,-modernize-use-nodiscard'
WarningsAsErrors: ''
HeaderFilterRegex: ''
AnalyzeTemporaryDtors: false
FormatStyle: file
User: vcarreira
CheckOptions:
- key: bugprone-use-after-move
value: '1'
- key: bugprone-argument-comment.StrictMode
value: '0'
- key: bugprone-assert-side-effect.AssertMacros
value: assert
- key: bugprone-assert-side-effect.CheckFunctionCalls
value: '0'
- key: bugprone-dangling-handle.HandleClasses
value: 'std::basic_string_view;std::experimental::basic_string_view'
- key: bugprone-exception-escape.FunctionsThatShouldNotThrow
value: ''
- key: bugprone-exception-escape.IgnoredExceptions
value: ''
- key: bugprone-misplaced-widening-cast.CheckImplicitCasts
value: '0'
- key: bugprone-sizeof-expression.WarnOnSizeOfCompareToConstant
value: '1'
- key: bugprone-sizeof-expression.WarnOnSizeOfConstant
value: '1'
- key: bugprone-sizeof-expression.WarnOnSizeOfIntegerExpression
value: '0'
- key: bugprone-sizeof-expression.WarnOnSizeOfThis
value: '1'
- key: bugprone-string-constructor.LargeLengthThreshold
value: '8388608'
- key: bugprone-string-constructor.WarnOnLargeLength
value: '1'
- key: bugprone-suspicious-enum-usage.StrictMode
value: '0'
- key: bugprone-suspicious-missing-comma.MaxConcatenatedTokens
value: '5'
- key: bugprone-suspicious-missing-comma.RatioThreshold
value: '0.200000'
- key: bugprone-suspicious-missing-comma.SizeThreshold
value: '5'
- key: bugprone-suspicious-string-compare.StringCompareLikeFunctions
value: ''
- key: bugprone-suspicious-string-compare.WarnOnImplicitComparison
value: '1'
- key: bugprone-suspicious-string-compare.WarnOnLogicalNotComparison
value: '0'
- key: bugprone-unused-return-value.CheckedFunctions
value: '::std::async;::std::launder;::std::remove;::std::remove_if;::std::unique;::std::unique_ptr::release;::std::basic_string::empty;::std::vector::empty'
- key: cert-dcl59-cpp.HeaderFileExtensions
value: ',h,hh,hpp,hxx'
- key: cert-err09-cpp.CheckThrowTemporaries
value: '1'
- key: cert-err61-cpp.CheckThrowTemporaries
value: '1'
- key: cert-msc32-c.DisallowedSeedTypes
value: 'time_t,std::time_t'
- key: cert-msc51-cpp.DisallowedSeedTypes
value: 'time_t,std::time_t'
- key: cert-oop11-cpp.IncludeStyle
value: llvm
- key: cppcoreguidelines-no-malloc.Allocations
value: '::malloc;::calloc'
- key: cppcoreguidelines-no-malloc.Deallocations
value: '::free'
- key: cppcoreguidelines-no-malloc.Reallocations
value: '::realloc'
- key: cppcoreguidelines-owning-memory.LegacyResourceConsumers
value: '::free;::realloc;::freopen;::fclose'
- key: cppcoreguidelines-owning-memory.LegacyResourceProducers
value: '::malloc;::aligned_alloc;::realloc;::calloc;::fopen;::freopen;::tmpfile'
- key: cppcoreguidelines-pro-bounds-constant-array-index.GslHeader
value: ''
- key: cppcoreguidelines-pro-bounds-constant-array-index.IncludeStyle
value: '0'
- key: cppcoreguidelines-pro-type-member-init.IgnoreArrays
value: '0'
- key: cppcoreguidelines-special-member-functions.AllowMissingMoveFunctions
value: '0'
- key: cppcoreguidelines-special-member-functions.AllowSoleDefaultDtor
value: '0'
- key: cppcoreguidelines-macro-usage.AllowedRegexp
value: 'ALWAYS_INLINE|SP_USE_FASTMATH'
- key: google-build-namespaces.HeaderFileExtensions
value: ',h,hh,hpp,hxx'
- key: google-global-names-in-headers.HeaderFileExtensions
value: ',h,hh,hpp,hxx'
- key: google-readability-braces-around-statements.ShortStatementLines
value: '1'
- key: google-readability-function-size.BranchThreshold
value: '4294967295'
- key: google-readability-function-size.LineThreshold
value: '4294967295'
- key: google-readability-function-size.NestingThreshold
value: '4294967295'
- key: google-readability-function-size.ParameterThreshold
value: '4294967295'
- key: google-readability-function-size.StatementThreshold
value: '800'
- key: google-readability-function-size.VariableThreshold
value: '4294967295'
- key: google-readability-namespace-comments.ShortNamespaceLines
value: '10'
- key: google-readability-namespace-comments.SpacesBeforeComments
value: '2'
- key: google-runtime-int.SignedTypePrefix
value: int
- key: google-runtime-int.TypeSuffix
value: ''
- key: google-runtime-int.UnsignedTypePrefix
value: uint
- key: google-runtime-references.WhiteListTypes
value: ''
- key: hicpp-braces-around-statements.ShortStatementLines
value: '1'
- key: hicpp-function-size.BranchThreshold
value: '4294967295'
- key: hicpp-function-size.LineThreshold
value: '4294967295'
- key: hicpp-function-size.NestingThreshold
value: '4294967295'
- key: hicpp-function-size.ParameterThreshold
value: '4294967295'
- key: hicpp-function-size.StatementThreshold
value: '800'
- key: hicpp-function-size.VariableThreshold
value: '4294967295'
- key: hicpp-member-init.IgnoreArrays
value: '0'
- key: hicpp-move-const-arg.CheckTriviallyCopyableMove
value: '1'
- key: hicpp-multiway-paths-covered.WarnOnMissingElse
value: '0'
- key: hicpp-named-parameter.IgnoreFailedSplit
value: '0'
- key: hicpp-no-malloc.Allocations
value: '::malloc;::calloc'
- key: hicpp-no-malloc.Deallocations
value: '::free'
- key: hicpp-no-malloc.Reallocations
value: '::realloc'
- key: hicpp-special-member-functions.AllowMissingMoveFunctions
value: '0'
- key: hicpp-special-member-functions.AllowSoleDefaultDtor
value: '0'
- key: hicpp-use-auto.MinTypeNameLength
value: '5'
- key: hicpp-use-auto.RemoveStars
value: '0'
- key: hicpp-use-emplace.ContainersWithPushBack
value: '::std::vector;::std::list;::std::deque'
- key: hicpp-use-emplace.SmartPointers
value: '::std::shared_ptr;::std::unique_ptr;::std::auto_ptr;::std::weak_ptr'
- key: hicpp-use-emplace.TupleMakeFunctions
value: '::std::make_pair;::std::make_tuple'
- key: hicpp-use-emplace.TupleTypes
value: '::std::pair;::std::tuple'
- key: hicpp-use-equals-default.IgnoreMacros
value: '1'
- key: hicpp-use-noexcept.ReplacementString
value: ''
- key: hicpp-use-noexcept.UseNoexceptFalse
value: '1'
- key: hicpp-use-nullptr.NullMacros
value: ''
- key: llvm-namespace-comment.ShortNamespaceLines
value: '1'
- key: llvm-namespace-comment.SpacesBeforeComments
value: '1'
- key: misc-definitions-in-headers.HeaderFileExtensions
value: ',h,hh,hpp,hxx'
- key: misc-definitions-in-headers.UseHeaderFileExtension
value: '1'
- key: misc-throw-by-value-catch-by-reference.CheckThrowTemporaries
value: '1'
- key: misc-unused-parameters.StrictMode
value: '0'
- key: misc-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic
value: '1'
- key: modernize-loop-convert.MaxCopySize
value: '16'
- key: modernize-loop-convert.MinConfidence
value: reasonable
- key: modernize-loop-convert.NamingStyle
value: CamelCase
- key: modernize-make-shared.IgnoreMacros
value: '1'
- key: modernize-make-shared.IncludeStyle
value: 'llvm'
- key: modernize-make-shared.MakeSmartPtrFunction
value: 'std::make_shared'
- key: modernize-make-shared.MakeSmartPtrFunctionHeader
value: memory
- key: modernize-make-unique.IgnoreMacros
value: '1'
- key: modernize-make-unique.IncludeStyle
value: 'llvm'
- key: modernize-make-unique.MakeSmartPtrFunction
value: 'std::make_unique'
- key: modernize-make-unique.MakeSmartPtrFunctionHeader
value: memory
- key: modernize-pass-by-value.IncludeStyle
value: llvm
- key: modernize-pass-by-value.ValuesOnly
value: '0'
- key: modernize-raw-string-literal.ReplaceShorterLiterals
value: '0'
- key: modernize-replace-auto-ptr.IncludeStyle
value: llvm
- key: modernize-replace-random-shuffle.IncludeStyle
value: llvm
- key: modernize-use-auto.MinTypeNameLength
value: '5'
- key: modernize-use-auto.RemoveStars
value: '0'
- key: modernize-use-default-member-init.IgnoreMacros
value: '1'
- key: modernize-use-default-member-init.UseAssignment
value: '0'
- key: modernize-use-emplace.ContainersWithPushBack
value: '::std::vector;::std::list;::std::deque'
- key: modernize-use-emplace.SmartPointers
value: '::std::shared_ptr;::std::unique_ptr;::std::auto_ptr;::std::weak_ptr'
- key: modernize-use-emplace.TupleMakeFunctions
value: '::std::make_pair;::std::make_tuple'
- key: modernize-use-emplace.TupleTypes
value: '::std::pair;::std::tuple'
- key: modernize-use-equals-default.IgnoreMacros
value: '1'
- key: modernize-use-noexcept.ReplacementString
value: ''
- key: modernize-use-noexcept.UseNoexceptFalse
value: '1'
- key: modernize-use-nullptr.NullMacros
value: 'NULL'
- key: modernize-use-transparent-functors.SafeMode
value: '0'
- key: modernize-use-using.IgnoreMacros
value: '1'
- key: performance-faster-string-find.StringLikeClasses
value: 'std::basic_string'
- key: performance-for-range-copy.WarnOnAllAutoCopies
value: '0'
- key: performance-inefficient-string-concatenation.StrictMode
value: '0'
- key: performance-inefficient-vector-operation.VectorLikeClasses
value: '::std::vector'
- key: performance-move-const-arg.CheckTriviallyCopyableMove
value: '1'
- key: performance-move-constructor-init.IncludeStyle
value: llvm
- key: performance-type-promotion-in-math-fn.IncludeStyle
value: llvm
- key: performance-unnecessary-value-param.IncludeStyle
value: llvm
- key: portability-simd-intrinsics.Std
value: ''
- key: portability-simd-intrinsics.Suggest
value: '0'
- key: readability-braces-around-statements.ShortStatementLines
value: '1'
- key: readability-function-size.BranchThreshold
value: '4294967295'
- key: readability-function-size.LineThreshold
value: '4294967295'
- key: readability-function-size.NestingThreshold
value: '4294967295'
- key: readability-function-size.ParameterThreshold
value: '4294967295'
- key: readability-function-size.StatementThreshold
value: '800'
- key: readability-function-size.VariableThreshold
value: '4294967295'
- key: readability-identifier-naming.IgnoreFailedSplit
value: '0'
- key: readability-implicit-bool-conversion.AllowIntegerConditions
value: '0'
- key: readability-implicit-bool-conversion.AllowPointerConditions
value: '0'
- key: readability-inconsistent-declaration-parameter-name.IgnoreMacros
value: '1'
- key: readability-inconsistent-declaration-parameter-name.Strict
value: '0'
- key: readability-simplify-boolean-expr.ChainedConditionalAssignment
value: '0'
- key: readability-simplify-boolean-expr.ChainedConditionalReturn
value: '0'
- key: readability-simplify-subscript-expr.Types
value: '::std::basic_string;::std::basic_string_view;::std::vector;::std::array'
- key: readability-static-accessed-through-instance.NameSpecifierNestingThreshold
value: '3'
- key: bugprone-stringview-nullptr
value: '1'
- key: cppcoreguidelines-avoid-do-while.IgnoreMacros
value: '1'
...
+10
View File
@@ -0,0 +1,10 @@
{
"configurations": [
{
"compileCommands": "${workspaceFolder}/build/debug/compile_commands.json",
"cppStandard": "c++23"
}
],
"version": 4
}
+12
View File
@@ -0,0 +1,12 @@
{
"testMate.cpp.test.advancedExecutables": [
{
"pattern": "${workspaceFolder}/build/*-tests",
"runTask": {
"before": [
"CMake: build"
]
}
}
],
}
+16
View File
@@ -0,0 +1,16 @@
{
"version": "2.0.0",
"tasks": [
{
"type": "cmake",
"label": "CMake: build",
"command": "build",
"targets": [
"all"
],
"group": "build",
"problemMatcher": [],
"detail": "CMake template build task"
}
]
}
+7 -2
View File
@@ -30,15 +30,20 @@ include(Catch)
set(CMAKE_C_COMPILER /opt/homebrew/Cellar/llvm@16/16.0.6/bin/clang) set(CMAKE_C_COMPILER /opt/homebrew/Cellar/llvm@16/16.0.6/bin/clang)
set(CMAKE_CXX_COMPILER /opt/homebrew/Cellar/llvm@16/16.0.6/bin/clang++) set(CMAKE_CXX_COMPILER /opt/homebrew/Cellar/llvm@16/16.0.6/bin/clang++)
SET(CALCULATOR_CHALLENGE_SOURCES
Calculator.cpp
)
add_executable(calculator-challege add_executable(calculator-challege
main.cpp main.cpp
${CALCULATOR_CHALLENGE_SOURCES}
) )
target_link_libraries(calculator-challege PRIVATE fmt::fmt) target_link_libraries(calculator-challege PRIVATE fmt::fmt)
add_executable(calculator-challege-tests add_executable(calculator-challege-tests
tests.cpp CalculatorTests.cpp
${CALCULATOR_CHALLENGE_SOURCES}
) )
target_link_libraries(calculator-challege-tests PRIVATE Catch2::Catch2WithMain) target_link_libraries(calculator-challege-tests PRIVATE Catch2::Catch2WithMain)
catch_discover_tests(calculator-challege-tests) catch_discover_tests(calculator-challege-tests)
+80
View File
@@ -0,0 +1,80 @@
#include "Calculator.hpp"
#include <ranges>
#include <unordered_map>
#include "Operand.hpp"
namespace {
using Workspace = std::unordered_map<std::string, double>;
class Visitor;
auto compute(Visitor& visitor, const Operation& binary_operation) noexcept -> std::optional<double>;
class Visitor
{
public:
Visitor(std::span<const Operation> operations, Workspace& variables) noexcept :
_operations{operations}, _variables{variables}
{}
auto operator()(const IntegerOperand& operand) noexcept -> std::optional<double> { return operand.get(); }
auto operator()(const VariableOperand& operand) noexcept -> std::optional<double>
{
auto name = operand.get();
auto found_variable = _variables.get().find(name);
if (found_variable != _variables.get().end()) return found_variable->second;
auto found_operation = std::ranges::find(_operations, name, &Operation::variable);
if (found_operation == _operations.end()) return std::nullopt;
return compute(*this, *found_operation);
}
private:
std::span<const Operation> _operations;
std::reference_wrapper<Workspace> _variables;
};
auto compute(Visitor& visitor, const Operation& operation) noexcept -> std::optional<double>
{
auto lhs = std::visit(visitor, operation.lhs);
if (!lhs.has_value()) return std::nullopt;
auto rhs = std::visit(visitor, operation.rhs);
if (!rhs.has_value()) return std::nullopt;
return operation.binary_op(lhs.value(), rhs.value());
}
} // namespace
void Calculator::addOperation(Operation operation) noexcept
{
_operations.push_back(std::move(operation));
}
void Calculator::addOperation(std::string result, Operand lhs, Operand rhs, Operator binary_operator) noexcept
{
addOperation(Operation{std::move(result), std::move(lhs), std::move(rhs), std::move(binary_operator)});
}
void Calculator::undoOperation(std::size_t count) noexcept
{
count = std::min(_operations.size(), count);
_operations.erase(_operations.end() - static_cast<std::int64_t>(count), _operations.end());
}
auto Calculator::result() noexcept -> double
{
Workspace workspace;
Visitor visitor{_operations, workspace};
for (auto& operation : std::views::reverse(_operations)) {
auto result = compute(visitor, operation);
if (result.has_value()) return result.value();
}
return 0.0;
}
+41
View File
@@ -0,0 +1,41 @@
#ifndef CALCULATOR_CHALLENGE_WORKSPACE_HPP
#define CALCULATOR_CHALLENGE_WORKSPACE_HPP
#include <cstdint>
#include <stack>
#include <string>
#include <unordered_map>
#include <vector>
#include "Operand.hpp"
struct Operation
{
std::string variable;
Operand lhs;
Operand rhs;
Operator binary_op;
};
class Calculator
{
public:
Calculator() noexcept = default;
Calculator(const Calculator&) noexcept = default;
Calculator(Calculator&&) noexcept = default;
auto operator=(const Calculator&) noexcept -> Calculator& = default;
auto operator=(Calculator&&) noexcept -> Calculator& = default;
~Calculator() noexcept = default;
void addOperation(Operation operation) noexcept;
void addOperation(std::string result, Operand lhs, Operand rhs, Operator binary_operator) noexcept;
void undoOperation(std::size_t count) noexcept;
auto result() noexcept -> double;
private:
std::vector<Operation> _operations;
};
#endif
+80
View File
@@ -0,0 +1,80 @@
#include <catch2/catch_test_macros.hpp>
#include "Calculator.hpp"
#include "Operand.hpp"
constexpr auto addiction = [](auto lhs, auto rhs) { return lhs + rhs; };
constexpr auto subtraction = [](auto lhs, auto rhs) { return lhs - rhs; };
TEST_CASE("Calculator - can add operations", "[calculator-challenge]")
{
Calculator calculator;
calculator.addOperation("a", IntegerOperand{5}, IntegerOperand{10}, addiction);
CHECK(calculator.result() == 15.0);
calculator.addOperation("b", IntegerOperand{1}, IntegerOperand{5}, addiction);
CHECK(calculator.result() == 6.0);
calculator.addOperation("c", IntegerOperand{1}, IntegerOperand{5}, subtraction);
CHECK(calculator.result() == -4.0);
}
TEST_CASE("Calculator - can undo operations", "[calculator-challenge]")
{
Calculator calculator;
calculator.addOperation("a", IntegerOperand{5}, IntegerOperand{10}, addiction);
CHECK(calculator.result() == 15.0);
calculator.addOperation("b", IntegerOperand{1}, IntegerOperand{5}, subtraction);
CHECK(calculator.result() == -4.0);
SECTION("one by one")
{
calculator.undoOperation(1);
CHECK(calculator.result() == 15.0);
calculator.undoOperation(1);
CHECK(calculator.result() == 0.0);
}
SECTION("all")
{
calculator.undoOperation(2);
CHECK(calculator.result() == 0.0);
}
SECTION("more than was added")
{
calculator.undoOperation(50);
CHECK(calculator.result() == 0.0);
}
}
TEST_CASE("Calculator - can add operations with variables", "[calculator-challenge]")
{
Calculator calculator;
calculator.addOperation("a", IntegerOperand{1}, IntegerOperand{2}, addiction);
CHECK(calculator.result() == 3);
calculator.addOperation("b", VariableOperand{"a"}, IntegerOperand{10}, addiction);
CHECK(calculator.result() == 13);
calculator.addOperation("b", VariableOperand{"a"}, IntegerOperand{2}, addiction);
CHECK(calculator.result() == 5);
}
TEST_CASE("Calculator - if a variable is missing the last available is returned", "[calculator-challenge]")
{
Calculator calculator;
calculator.addOperation("a", VariableOperand{"c"}, IntegerOperand{10}, addiction);
CHECK(calculator.result() == 0.0);
calculator.addOperation("a", IntegerOperand{1}, IntegerOperand{2}, addiction);
CHECK(calculator.result() == 3);
calculator.addOperation("a", VariableOperand{"c"}, IntegerOperand{10}, addiction);
CHECK(calculator.result() == 3.0);
}
+34
View File
@@ -0,0 +1,34 @@
#ifndef CALCULATOR_CHALLENGE_OPERAND_HPP
#define CALCULATOR_CHALLENGE_OPERAND_HPP
#include <functional>
#include <string>
#include <variant>
template<typename T>
using BinaryOperatorType = std::function<T(T, T)>;
using Operator = BinaryOperatorType<double>;
class IntegerOperand
{
public:
explicit IntegerOperand(double value) noexcept : _value{value} {}
auto get() const noexcept -> double { return _value; };
private:
double _value{0};
};
class VariableOperand
{
public:
explicit VariableOperand(std::string name) noexcept : _name{std::move(name)} {}
auto get() const noexcept -> std::string { return _name; };
private:
std::string _name;
};
using Operand = std::variant<IntegerOperand, VariableOperand>;
#endif
-15
View File
@@ -1,15 +0,0 @@
#include <catch2/catch_test_macros.hpp>
#include <cstdint>
uint32_t factorial(uint32_t number)
{
return number <= 1 ? number : factorial(number - 1) * number;
}
TEST_CASE("Placeholder", "[testing]")
{
REQUIRE(factorial(1) == 1);
REQUIRE(factorial(2) == 2);
REQUIRE(factorial(3) == 6);
REQUIRE(factorial(10) == 3'628'800);
}