Skip to content

Instantly share code, notes, and snippets.

@pombadev
Last active October 12, 2016 18:09
Show Gist options
  • Save pombadev/9b14a18eb0a9f3b03d6e4ffeb8b9ed5b to your computer and use it in GitHub Desktop.
Save pombadev/9b14a18eb0a9f3b03d6e4ffeb8b9ed5b to your computer and use it in GitHub Desktop.
Reverse or rotate given string.
function revrot(str, sz) {
/**
* If string (str), size (sz) or size is greater than string's
* length, return empty string.
*/
if (sz === 0 || str.length === 0 || sz > str.length) {
return ''
}
const
/**
* Splits string into groups of size provided
* @param {String} string
* @param {Number} size
* @return {Array}
*/
splitter = (string) => {
/* Pattern to split string into groups, in our case provided size */
let pattern = new RegExp(`.{1,${sz}}`, 'g')
return string.match(pattern)
},
chunked = splitter(str),
/**
* Get sum of the cubes of each elements
* @param {String} element
* @return {Array}
*/
sumOfCubes = chunked.map(element => {
return Array.prototype.reduce.call(element, (init, next) => {
init = init + Math.pow(Number(next), 3);
return init;
}, 0);
}),
/**
* Check if number is divisble by 2
* @param {Number} n
* @return {Boolean}
*/
isDivisibleByTwo = n => n % 2 === 0,
/**
* Map sumOfCubes & chunked array together
* @return {Array} Array of objects
*/
mapElements = chunked.map((e, i) => {
return {
chunked: chunked[i],
sumOfCubes: sumOfCubes[i]
};
}),
/* Final maped array */
finalMapedArray = mapElements.map(num => {
/* Ignore chunk if it's size is less than sz */
if (num.chunked.length === sz) {
if (isDivisibleByTwo(num.sumOfCubes)) {
/* Reversing the string */
return num.chunked.split('').reverse().join('')
} else {
/* Rotating the string to the left by one position */
return num.chunked[1] + num.chunked.slice(2) + num.chunked[0]
}
}
})
return finalMapedArray.join('')
}
// console.log('Final', revrot('123456779', 8) === '23456771')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment