17  Basic Mathematical Operations

8kyu Tantangan #17/366 - 02 Mar 2024

https://www.codewars.com/kata/57356c55867b9b7a60000bd7

17.1 Instruction

Your task is to create a function that does four basic mathematical operations.

The function should take three arguments - operation(string/char), value1(number), value2(number). The function should return result of numbers after applying the chosen operation.

Examples(Operator, value1, value2) –> output

('+', 4, 7) --> 11
('-', 15, 18) --> -3
('*', 5, 5) --> 25
('/', 49, 7) --> 7

17.2 YouTube Video

17.3 Solution Code

basic_op <- function(operator, value1, value2){
 eval(parse(text = paste0(value1, operator, value2)))
}
basic_op <- function(operator, value1, value2){
 eval(str2lang(paste0(value1, operator, value2)))
}

17.4 Test

library(testthat)

test_that('Basic tests', {
  expect_equal(basic_op('+', 4, 7), 11)
  expect_equal(basic_op('-', 15, 18), -3)
  expect_equal(basic_op('*', 5, 5), 25)
  expect_equal(basic_op('/', 49, 7), 7)
})
Test passed 🎊

17.5 Supported by

StarCore Analytics