Issue when creating from scratch toUpperCase function - javascript

I've been tasking with creating my own version of the toUpperCase() fucntion in JavaScript. This is what I have come up with. We were given a tester file and denied access to the source code. My output is as follows:
function stringToUppercase(string) {
/*
upper = ['A','B','C', etc...]
compare lowerY to upperY get index numbers of lowercase[y] that matches and use those to
create matching values at upperCase[y]
will print newString based on compared upper and lower values
*/
const upperCase = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
const lowerCase = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
const numbers = ['0','1','2','3','4','5','6','7','8','9'];
const specialChar = ['`','~','!','#','#','$','%','^','&','*','(',')','-','_','+','=','{','}','[',']','|',';',':','"','<'];
let newString = "";
for (let x = 0; x < string.length; x++){
for (let y = 0; y < lowerCase.length; y++) {
if (string[x] === lowerCase[y] || string[x] === upperCase[y]) {
newString += upperCase[y];
} else if (string[x] === '\n' || string[x] === '\t' || string[x] === ' '){
newString += string[x];
} else if (string[x] === numbers[y]) {
newString += string[x];
} else if (string[x] === specialChar[y]) {
newString += string[x];
}
}
}
return newString;
}

I have coded it up again, but this time following your requirements:
function stringToUppercase(string) {
const lowerCase = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
const upperCase = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var newString = "";
outer:
for (var char = 0; char < string.length; char ++) {
for (var letter = 0; letter < lowerCase.length; letter ++) {
if (string[char] == lowerCase[letter]) {
newString += upperCase[letter];
continue outer;
}
}
newString += string[char];
}
return newString;
}

I have coded up a much more efficient 'stringToUppercase' function for you:
function stringToUppercase(string) {
const lowerCase = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
const upperCase = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var newString = string;
for (var char = 0; char < lowerCase.length; char += 1) {
for (var x = 0; x < string.split(lowerCase[char]).length; x += 1) {
newString = newString.replace(lowerCase[char], upperCase[char]);
}
}
return newString;
}

Here's probably the most efficient solution.
function stringToUppercase(str) {
let out = "";
for (let i=0; i<str.length; i++) {
let charCode = str.charCodeAt(i);
if (charCode >= 0x61 && charCode <= 0x7A)
out += String.fromCharCode(charCode - 0x20);
else
out += str[i];
}
return out;
}
However, since you can't use built-in functions:
function stringToUppercase(string) {
const caseMap = {"a":"A", "b":"B", "c":"C", "d":"D", "e":"E", "f":"F", "g":"G", "h":"H", "i":"I", "j":"J", "k":"K", "l":"L", "m":"M", "n":"N", "o":"O", "p":"P", "q":"Q", "r":"R", "s":"S", "t":"T", "u":"U", "v":"V", "w":"W", "x":"X", "y":"Y", "z":"Z"}
var newString = "";
for (var i = 0; i < string.length; i += 1) {
const char = string[i];
if (char in caseMap)
newString += caseMap[char];
else
newString += char;
}
return newString;
}

Related

How to return an error with JavaScript when someone enter just space on name field in a array? [duplicate]

This question already has answers here:
How to detect string which contains only spaces?
(10 answers)
Closed 2 years ago.
Here is a code for finding the largest word from an array. But When I input some space (" ") like this I get the blank one as largest. But I want if anyone entered some space only it will return an error.
Can anyone tell me how to do that?
function megaFriend(str) {
var wordLength = 0;
var biggestWord;
for (var i = 0; i < str.length; i++) {
if (str[i].length > wordLength) {
var wordLength = str[i].length;
biggestWord = str[i];
}
}
return biggestWord;
}
console.log(megaFriend(['Nahid', 'Hassan', 'Ahugoggghs', ' ']));
you can use str.replaceAll() method
let spaceFreeElement = str[i].replaceAll(" ", "");
or regex
let spaceFreeElement = str[i].replace(/\s/g, "")
Use a regular expression to test if a word is just spaces, and report an error.
function megaFriend(str) {
var wordLength = 0;
var biggestWord;
for (var i = 0; i < str.length; i++) {
if (str[i].match(/^\s+$/)) {
alert("Spaces entered");
return false;
}
if (str[i].length > wordLength) {
var wordLength = str[i].length;
biggestWord = str[i];
}
}
return biggestWord;
}
console.log(megaFriend(['Nahid', 'Hassan', 'Ahugoggghs', ' ']));
An easy solution is to String.trim() the words when you check the length:
function megaFriend(str) {
var wordLength = 0;
var biggestWord;
for (var i = 0; i < str.length; i++) {
if (str[i].trim().length > wordLength) {
var wordLength = str[i].length;
biggestWord = str[i];
}
}
return biggestWord;
}
console.log(megaFriend(['Nahid', 'Hassan', 'Ahugoggghs', ' ']));
You can also trim and throw an error if the string's length is 0 after trimming:
function megaFriend(str) {
var wordLength = 0;
var biggestWord;
for (var i = 0; i < str.length; i++) {
if(str[i].trim().length === 0 && str[i].length > 0) {
throw new Error(`illegal string - index ${i}`);
}
if (str[i].length > wordLength) {
var wordLength = str[i].length;
biggestWord = str[i];
}
}
return biggestWord;
}
console.log(megaFriend(['Nahid', 'Hassan', 'Ahugoggghs', ' ']));

Given n as input, print the following pattern -1+2-3+4-5+....(+/-)n = n, with JavaScript

I have tried many times but I can't find the values, how can I solve this? Here's my code:
var number = prompt("");
for (var count = 1; count <= number; count++) {
if (count % 2 != 0) {
console.log("-");
document.write("-");
// console.log(count);
document.write(count);
} else {
console.log("+");
document.write("+");
// console.log(count);
document.write(count);
}
}
document.write("=", );
Try this out:
var number = prompt("");
var result = 0;
for (var count = 1; count <= number; count++) {
if (count % 2 != 0) {
document.write("-");
document.write(count);
result -= count;
} else {
document.write("+");
document.write(count);
result += count;
}
}
document.write("=" + result);
A declarive solution. (as a fan of declarative programming)
const func = (n) => {
[...Array(n)].map( (_,i) => (
i%2 === 0 ? console.log(`-${i+1}`) : console.log(`+${i+1}`)
))}
func(6)
This should do the trick.
Here's your solution (with fiddle).
function expandString(n) {
let str = '';
for (let i = 1; i <= n; i++) {
if (i % 2 === 1) {
str += `-${i}`; // Even
} else {
str += `+${i}`; // Odd
}
}
return str += ` = ${n}`;
}
console.log(expandString(5));
Hope this will help you.
var flag = true;
var result=0;
var str = "";
var n=10;
for(let i=1;i<n;i++){
if(flag){
str += "-";
result -= i;
}
else{
str += "+";
result += i;
}
str += i;
flag = !flag
}
str += "="+result;
console.log(str);

How do you iterate over an array every x spots and replace with letter?

/Write a function called weave that accepts an input string and number. The function should return the string with every xth character replaced with an 'x'./
function weave(word,numSkip) {
let myString = word.split("");
numSkip -= 1;
for(let i = 0; i < myString.length; i++)
{
numSkip += numSkip;
myString[numSkip] = "x";
}
let newString = myString.join();
console.log(newString);
}
weave("weave",2);
I keep getting an infinite loop. I believe the answer I am looking for is "wxaxe".
Here's another solution, incrementing the for loop by the numToSkip parameter.
function weave(word, numToSkip) {
let letters = word.split("");
for (let i=numToSkip - 1; i < letters.length; i = i + numToSkip) {
letters[i] = "x"
}
return letters.join("");
}
Well you need to test each loop to check if it's a skip or not. Something as simple as the following will do:
function weave(word,numSkip) {
var arr = word.split("");
for(var i = 0; i < arr.length; i++)
{
if((i+1) % numSkip == 0) {
arr[i] = "x";
}
}
return arr.join("");
}
Here is a working example
Alternatively, you could use the map function:
function weave(word, numSkip) {
var arr = word.split("");
arr = arr.map(function(letter, index) {
return (index + 1) % numSkip ? letter : 'x';
});
return arr.join("");
}
Here is a working example
Here is a more re-usable function that allows specifying the character used for substitution:
function weave(input, skip, substitute) {
return input.split("").map(function(letter, index) {
return (index + 1) % skip ? letter : substitute;
}).join("");
}
Called like:
var result = weave('weave', 2, 'x');
Here is a working example
You dont need an array, string concatenation will do it, as well as the modulo operator:
function weave(str,x){
var result = "";
for(var i = 0; i < str.length; i++){
result += (i && (i+1)%x === 0)?"x":str[i];
}
return result;
}
With arrays:
const weave = (str,x) => str.split("").map((c,i)=>(i&&!((i+1)%x))?"x":c).join("");
You're getting your word greater in your loop every time, so your loop is infinite.
Try something like this :
for(let k = 1; k <= myString.length; k++)
{
if(k % numSkip == 0){
myString[k-1]='x';
}
}
Looking at what you have, I believe the reason you are getting an error is because the way you update numSkip, it eventually becomes larger than
myString.length. In my code snippet, I make i increment by numSkip which prevents the loop from ever executing when i is greater than myString.length. Please feel free to ask questions, and I will do my best to clarify!
JSFiddle of my solution (view the developer console to see the output.
function weave(word,numSkip) {
let myString = word.split("");
for(let i = numSkip - 1; i < myString.length; i += numSkip)
{
myString[i] = "x";
}
let newString = myString.join();
console.log(newString);
}
weave("weave",2);
Strings are immutable, you need a new string for the result and concat the actual character or the replacement.
function weave(word, numSkip) {
var i, result = '';
for (i = 0; i < word.length; i++) {
result += (i + 1) % numSkip ? word[i] : 'x';
}
return result;
}
console.log(weave("weave", 2));
console.log(weave("abcd efgh ijkl m", 5));
You can do this with fewer lines of code:
function weave(word, numSkip) {
word = word.split("");
for (i = 0; i < word.length; i++) {
word[i] = ((i + 1) % numSkip == 0) ? "x" : word[i];
}
return word.join("");
}
var result = weave("weave", 2);
console.log(result);

Identify palindromes in a sentence

A lot of solutions I found here are giving true or false after checking if a string is a palindrome. I have a function that checks if a string is a palindrome or not:
function palindrome(myString){
/* remove special characters, spaces and make lowercase*/
var removeChar = myString.replace(/[^A-Z0-9]/ig, "").toLowerCase();
/* reverse removeChar for comparison*/
var checkPalindrome = removeChar.split('').reverse().join('');
/* Check to see if myString is a Palindrome*/
if(removeChar === checkPalindrome){
document.write("<div>"+ myString + " is a Palindrome <div>");
}else{
document.write("<div>" + myString + " is not a Palindrome </div>");
}
}
palindrome("Oh who was it I saw, oh who?")
palindrome("Madam")
palindrome("Star Wars")
But this is not quite what I want. It's just checking if the string is a palindrome or not. I want to update the function so that it identifies all of the palindromes in a sentence instead of giving it true or false. So if there's a sentence like this - "Madam and John went out at noon" It will list the palindromes in that sentence - "Madam, noon"
Any help in this would be appreciated!
function findPalindromes(str, min) {
min = min || 3;
var result = [];
var reg = str.toLowerCase();
var reg = reg.replace(/[^a-z]/g, ''); // remove if you want spaces
var rev = reg.split("").reverse().join("");
var l = reg.length;
for (var i = 0; i < l; i++) {
for (var j = i + min; j <= l; j++) {
var regs = reg.substring(i, j);
var revs = rev.substring(l - j, l - i);
if (regs == revs) {
result.push(regs);
}
}
}
return result;
}
var str1 = "Madam and John went out at noon";
console.log(str1, findPalindromes(str1));
var str2 = "\"Amore, Roma\" and \"There's no 'x' in Nixon\" are palindromes.";
console.log(str2, findPalindromes(str2));
function findPalindromes(sentence) {
const words = sentence.replace(/[^\w\s]/gi, '').split(' ');
const palindromes = words.filter(isPalindrome);
return palindromes;
}
function isPalindrome(word) {
if (word.length <= 0) return false;
word = word.toLowerCase();
for (let i = 0; i < word.length / 2; i++) {
if (word[i] !== word[word.length - 1 - i]) return false;
}
return true;
}
https://jsfiddle.net/ewezbz22/1/

Insert dashes into a number

Any ideas on the following? I want to input a number into a function and insert dashes "-" between the odd digits. So 4567897 would become "456789-7". What I have so far is to convert the number into a string and then an array, then look for two odd numbers in a row and use the .splice() method to add the dashes where appropriate. It does not work and I figure I may not be on the right track anyway, and that there has to be a simpler solution.
function DashInsert(num) {
var numArr = num.toString().split('');
for (var i = 0; i < numArr.length; i++){
if (numArr[i]%2 != 0){
if (numArr[i+1]%2 != 0) {
numArr.splice(i, 0, "-");
}
}
}
return numArr;
}
The problem is you're changing the thing you're iterating over. If instead you maintain a separate output and input...
function insertDashes(num) {
var inStr = String(num);
var outStr = inStr[0], ii;
for (ii = 1; ii < inStr.length; ii++) {
if (inStr[ii-1] % 2 !== 0 && inStr[ii] % 2 !== 0) {
outStr += '-';
}
outStr += inStr[ii];
}
return outStr;
}
You can try using regular expressions
'4567897'.replace(/([13579])(?=[13579])/g, '$1-')
Regex Explained
So, we find an odd number (([13579]) is a capturing group meaning we can use it as a reference in the replacement $1) ensure that it is followed by another odd number in the non-capturing positive lookahead ((?=[13579])) and replace the matched odd number adding the - prefix
Here is the function to do it:
function dashes(number){
var numString = '';
var numArr = number.toString().split('');
console.log(numArr);
for(i = 0; i < numArr.length; i++){
if(numArr[i] % 2 === 1 && numArr[i+1] % 2 === 1){
numString += numArr[i] + '-';
}else{
numString += numArr[i];
}
}
console.log(numString);
}
dashes(456379);
Tested and everything.
Edit: OrangeDog's answer was posted earlier (by nearly a full half hour), I just wanted to make an answer which uses your code since you're almost there.
Using another array instead of splicing into one you were looping through (this happens to return a string using join):
var num = 4567897;
function DashInsert(num) {
var numArr = num.toString().split('');
var len = numArr.length;
var final = [];
for (var i = 0; i < len; i++){
final.push(numArr[i]);
if (numArr[i]%2 != 0){
if (i+1 < len && numArr[i+1]%2 != 0) {
final.push("-")
}
}
}
return final.join("");
}
alert(DashInsert(num));
function dashInsert(str) {
var arrayNumbers = str.split("");
var newString = "";
for (var i = 0; i < arrayNumbers.length; i++){
if(arrayNumbers[i] % 2 === 1 && arrayNumbers[i + 1] % 2 === 1){
newString = newString + arrayNumbers[i] + "-";
} else {
newString = newString + arrayNumbers[i];
}
}
return newString;
}
var result = dashInsert("3453246");
console.log(result);

Categories

Resources