Skip to content

Instantly share code, notes, and snippets.

@ChousinRahit
Last active September 3, 2023 11:00
Show Gist options
  • Save ChousinRahit/f58c0d82ee54443f8481afba2ace331f to your computer and use it in GitHub Desktop.
Save ChousinRahit/f58c0d82ee54443f8481afba2ace331f to your computer and use it in GitHub Desktop.
// Move Capital Letters to the Front
// Create a function that moves all capital letters to the front of a word.
// Examples
// capToFront("hApPy") ➞ "APhpy"
// capToFront("moveMENT") ➞ "MENTmove"
// capToFront("shOrtCAKE") ➞ "OCAKEshrt"
// Pseudocode
// Write a function with name "capToFront" that takes a string argument
// declare a variable to store CapitalLetters - "caps"
// declare a variable to store lowercase letters - "lows"
// Convert the string to array and loop through
// have an if else condition to check if the letter is UPPERCASE or not
// if UPPERCASE is concat it to "caps" else concat to "lows"
// return the "caps" and "lows" concated together
// SOLUTION 1
function capToFront(str) {
const uppercase = [];
const lowercase = [];
[...str].forEach(char => {
if (char === char.toUpperCase()) {
uppercase.push(char);
} else {
lowercase.push(char);
}
});
// return uppercase.concat(lowercase).join('');
return [...uppercase, ...lowercase].join('');
}
console.log(capToFront('hApPy'));
console.log(capToFront('moveMENT'));
// SOLUTION 2 - using string concatenation
function capToFrontSol2(str) {
let caps = '';
let lows = '';
[...str].forEach(char => {
if (char === char.toUpperCase()) {
caps = caps + char;
} else {
lows = lows + char;
}
});
return caps + lows;
}
console.log(capToFrontSol2('hApPy'));
console.log(capToFrontSol2('moveMENT'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment