Skip to content

Instantly share code, notes, and snippets.

@juliovedovatto
Last active January 21, 2021 01:41
Show Gist options
  • Save juliovedovatto/4a23b8c7c771d270e63570a92fcccac5 to your computer and use it in GitHub Desktop.
Save juliovedovatto/4a23b8c7c771d270e63570a92fcccac5 to your computer and use it in GitHub Desktop.
exercise to move capital letter to the front of a string
/**
* Create a function that moves all capital letters to the front of
* a string/word. Keep the original relative
* order of all letters the same.
*
* Example:
*
* "hApPy" ➞ "APhpy"
*/
function inRange(number, starts, end) {
return ( (number - starts) * (number - end) <= 0 )
}
function sortStr(str) {
// solution 1
// return str.split('').sort((a,b) => a > b ? 1 : a === b ? 0 : - 1).join('')
// sollution 2 (with regexp)
// const lowerCaseRegexp = /[a-z]/
// return [...str].sort((a,b) => lowerCaseRegexp.test(a) ? 1 : lowerCaseRegexp.test(b) ? -1 : 0).join('')
// solution 3 (with ASCII code)
const upperCaseCodes = [65, 90] // ASCII codes for A-Z chars
return [...str].sort((a,b) => inRange(a.charCodeAt(), ...upperCaseCodes) ? -1 : !inRange(b.charCodeAt(), ...upperCaseCodes) ? 1 : 0).join('')
}
console.log(sortStr('hApPy')) // "APhpy"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment