I have to do this simple exercise but I am really struggling a lot with it. I have to convert all the names to uppercase and pass it to the empty array, using only while loop(s), and I can't use any method, just plain javascript 5:
var names = ['rob', 'dwayne', 'james', 'larry', 'steve'];
var UpperCase = [];
I tried with an object like this (there are still some mistakes, it's just an idea):
var change = {
"mary":"MARY",
"john":"JOHN",
"james":"JAMES",
"anna":"ANNA",
"jack":"JACK",
"jeremy":"JEREMY",
"susanne":"SUSANNE",
"caroline":"CAROLINE",
"heidi":"HEIDI"
}
for(var key in change) {
var obj = change[key];
for (var prop in obj) {
var value = obj[prop];
}
}
while(names[i]===change.key) {
for(var i=0; i<names.length; i++) {
UpperCase = change.value[i];
} }
I hope somebody can help me with this one.
Thanks!
Instead of using toUppercase():
Check if a character is uppercase or lowercase with this
str[i].charCodeAt(0) > 96
Using just while
var i = 0;
while (i < str.length) ...
Not using push function for array
UPPERCASE[UPPERCASE.length] = uppercase(names[i]);
I hope this function helps you
function uppercase(str) {
var i = 0;
var output = "";
while (i < str.length) {
var x =
(str[i].charCodeAt(0) > 96)
? String.fromCharCode(str[i].charCodeAt(0) - 32)
: String.fromCharCode(str[i].charCodeAt(0));
output += x;
i++;
}
return output;
}
Example:
function uppercase(str) {
var i = 0;
var output = "";
while (i < str.length) {
var x =
(str[i].charCodeAt(0) > 96) ?
String.fromCharCode(str[i].charCodeAt(0) - 32) :
String.fromCharCode(str[i].charCodeAt(0));
output += x;
i++;
}
return output;
}
var UPPERCASE = [];
var names = ["rOb", "dwayne", "james", "larry", "steve"];
var i = 0;
while (i < names.length) {
UPPERCASE[UPPERCASE.length] = uppercase(names[i]);
i++;
}
console.log(UPPERCASE);
Update
Answer without function and linear condition
var UPPERCASE = [];
var names = ["rOb", "dwayne", "james", "larry", "steve"];
var i = 0;
while (i < names.length) {
var j = 0,
output = "",
str = names[i];
while (j < str.length) {
var x;
if (str[j].charCodeAt(0) > 96) {
x = String.fromCharCode(str[j].charCodeAt(0) - 32);
} else {
x = String.fromCharCode(str[j].charCodeAt(0));
}
output += x;
j++;
}
UPPERCASE[UPPERCASE.length] = output;
i++;
}
console.log(UPPERCASE);