Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 41e0472

Browse files
author
root
committed
use ensure R func
1 parent 8ed3097 commit 41e0472

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

cachematrix.R

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ makeCacheMatrix <- function(x = matrix()) {
2020

2121
# update matrix value
2222
set <- function(newMatrix, inverse) {
23-
stopifnot_square(newMatrix)
23+
ensure_square_matrix(newMatrix)
2424
x<<-newMatrix
2525
inverse <<- NULL #new matrix invalidates old cache value
2626
}
@@ -29,7 +29,7 @@ makeCacheMatrix <- function(x = matrix()) {
2929

3030
# hard set inverse to X
3131
setInverse <- function(x) {
32-
stopifnot_square(x)
32+
ensure_square_matrix(x)
3333
inverse <<- x
3434
}
3535

@@ -48,13 +48,13 @@ makeCacheMatrix <- function(x = matrix()) {
4848
cacheSolve <- function(x, ...) {
4949

5050
## Basic sanity checks for input
51-
stopifnot(!is.null(x))
52-
stopifnot(!is.na(x))
53-
stopifnot(!is.matrix(x))
54-
stopifnot_square(x)
51+
ensure(is.null(x), 'Input is null')
52+
ensure(is.na(x), 'Input value is missing')
53+
ensure(is.matrix(x), 'Input is not a matrix')
54+
ensure_square_matrix(x)
55+
5556
## Try get result from cache, return result if found
5657
inverse <- x$getInverse()
57-
5858
if(!is.null(inverse)) {
5959
print('Return inverse from cache')
6060
return(inverse)
@@ -69,9 +69,13 @@ cacheSolve <- function(x, ...) {
6969
inverse
7070
}
7171

72-
stopifnot_square <-function(x) {
72+
ensure_square_matrix <-function(x) {
7373
d <- dim(x)
74-
ifelse((d[1] == d[2]), TRUE, stop('Not a square matrix'))
74+
ensure(!(d[1] == d[2]), 'Not a square matrix')
75+
}
76+
77+
ensure <- function(cond, message) {
78+
ifelse(cond, stop(message), TRUE)
7579
}
7680

7781
# Basic tests for validation

0 commit comments

Comments
 (0)