Recently, I had a test and I wrote this code, but they didn't like my code because it was "deplete and nested".
In order to improve my skills, what would be good ways to make this more readable and less deplete and nested?
Exercise
The validBraces
method takes a string of braces as a single parameter and determines if the order of the braces is valid. All input strings will only consist of open curly braces {
, closed curly braces }
, open parentheses (
, closed parentheses )
, and open brackets [
and closed brackets ]
.
- A string of braces is considered valid if all open braces are matched with their corresponding closed brace. For example:
(){}[]
and([{}])
would be considered valid, while(}
,[(])
, and[({})](]
would be considered invalid. - An empty string is considered valid.
- A non-string input is considered an invalid input. The method should throw an
InvalidArgumentException
in this case.
titleCase
A string is considered to be in title case if each word in the string is either:
- capitalised: that is, only the first letter of the word is in upper case; or
- considered to be an exception and put entirely into lower case unless it is the first word, which is always capitalised.
The titleCase
method will convert a string into titleCase
given an optional list of exceptions. The list of exception words will be given as an array of strings. The method should ignore the case of the exception word strings—it should behave in the same way even if the case of the exception word strings changes.
php
// should return: 'Do Androids Dream of Electric Sheep?'
->titleCase('do androids dream of electric SHEEP?', array('do', 'an', 'of'));
php
//should return: 'Rendezvous with Rama'
->titleCase('RENDEZVOUS WITH RAMA', array('With'));
php
// should return: 'Stranger In A Strange Land'
->titleCase('stranger in a strange land');
This is my code:
class StringUtil {
/**
* Verify a string of braces
*
* Takes a string of braces as a single parameter and determines if the order of the braces is
* valid.
*
* @access public
* @param String $braces
* @return Boolean
* @throws \InvalidArgumentException If $braces is not a string
*/
public function validBraces($braces = '') {
/**
* I assume that empty string is valid because
* is the default value
* and you have in the test as valid
*/
if ($braces === '') {
return true;
} elseif (empty($braces)) {
return false;
}
/**
* array of chars allowed,
* the keys are the open chars
* the values are the closure
*/
$symbols = array("(" => ")", "{" => "}", "[" => "]");
// get array with all characters allowed
$search = array_merge(array_keys($symbols), array_values($symbols));
//check valid string
if (\strlen(str_replace($search, '', $braces)) > 0) {
throw new \InvalidArgumentException("ERROR: Invalid Arguments. Just (){}[] characters allowed in the string");
}
//check if the length is even
if (\strlen($braces) % 2 !== 0) {
return false;
}
// Make sure start & end chars are not incorrect
if (in_array(substr($braces, 0, 1), $symbols) || array_key_exists(substr($braces, -1, 1), $symbols)) {
return false;
}
//Make sure the string have the same amount of open & end chars
foreach ($symbols as $key => $value) {
if (substr_count($braces, $key) !== substr_count($braces, $value)) {
return false;
}
}
$bracesArray = str_split($braces);
for ($i = 0; $i <= count($bracesArray) - 1; $i++) {
if (in_array($bracesArray[$i], $symbols)) {
if ($bracesArray[$i] === $symbols[$bracesArray[$i - 1]]) {
unset($bracesArray[$i], $bracesArray[$i - 1]);
break;
} else {
return false;
}
}
}
if (!empty($bracesArray)) {
$newBraces = implode("", $bracesArray);
return $this->validBraces($newBraces);
}
return true;
}
/**
* Convert a string into title case given an optional list of exceptions.
*
* @access public
* @param String $title
* @param Array $exceptions
* @return String
*/
public function titleCase($title, $exceptions = array()) {
$newExecption = array();
foreach ($exceptions as $execptionV) {
$newExecption[] = strtolower($execptionV);
}
$stringArray = explode(' ', $title);
foreach ($stringArray as $key => $value) {
if (empty($newExecption)) {
$new[] = ucfirst(strtolower($value));
} else {
if ($key == 0) {
$new[] = ucfirst(strtolower($value));
} else {
if (!in_array(strtolower($value), $newExecption)) {
$new[] = ucfirst(strtolower($value));
} else {
$new[] = strtolower($value);
}
}
}
}
$newPhrase = implode(" ", $new);
return $newPhrase;
}
}
Test for validBraces
:
public function validBraces() {
return array(
array('()'),
array('{}'),
array('[]'),
array('(){}[]'),
array('([{}])'),
array('{}({})[]'),
array('({})[({})]'),
array('(({{[[]]}}))'),
array('')
);
}
public function invalidBraces() {
return array(
array('(}'),
array('[(])'),
array('(})'),
array(')(}{]['),
array('())({}}{()][]['),
array('(((({{'),
array('}}]]))}])')
);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testInvalidArgumentException() {
$this->util->validBraces(1);
}
Test for titleCase
:
public function testDefault() {
$this->assertSame('Abc Def Ghi', $this->util->titleCase('aBC deF Ghi'));
}
public function testFirstWord() {
$this->assertSame('Ab', $this->util->titleCase('ab', array('ab')));
}
public function testExceptionWord() {
$this->assertSame('A bc', $this->util->titleCase('a bc', array('bc')));
}
public function testExceptionWordIgnoresCase() {
$this->assertSame('A bc', $this->util->titleCase('a bc', array('BC')));
}
public function testBogusExceptionWords() {
$this->assertSame('First A Of In', $this->util->titleCase(
'First a of in', array('an', 'often', 'into')
));
}
public function testTitles() {
$this->assertSame('A Clash of Kings', $this->util->titleCase(
'a clash of KINGS', array('a', 'an', 'the', 'OF')
));
$this->assertSame('The quick Brown fox', $this->util->titleCase(
'the QUICK bRoWn fOX', array('xyz', 'fox', 'quick', 'the')
));
}