Skip to content

Instantly share code, notes, and snippets.

@xpansive xpansive/LICENSE.txt forked from 140bytes/LICENSE.txt
Created Feb 25, 2012

Embed
What would you like to do?
rotateString in 55 bytes

Rotate string

This function will rotate a string either forwards or backwards, and does so in 9155 bytes. For example, "hello" shifted by 3 is "llohe" and "123456789" shifted by -37 is "234567891".

function(a, // The text to rotate
b) // The amount to shift by
{
return
a.slice(b%=a.length) // Get a slice starting at the shift amount and going to the end of the string
// Also modulo shift by the text length to make sure we stay inside
+a.slice(0,b) // Add on a slice from the beginning of the string to the shift amount
}
function(a,b){return a.slice(b%=a.length)+a.slice(0,b)}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Noah Weninger <https://github.com/xpansive>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "rotateString",
"description": "Rotates the text in strings either forwards or backwards.",
"keywords": [
"string",
"rotate",
"shift"
]
}
<!DOCTYPE html>
<title>rotateString example</title>
<pre id=out onmouseover="inc=-1" onmouseout="inc=1"></pre>
<script>
var rotateString = function(a,b){return a.slice(b%=a.length)+a.slice(0,b)};
var shift = 0, inc = 1;
setInterval(function() {
document.getElementById("out").innerHTML = rotateString("140byt.es rules! ", shift += inc);
}, 100);
</script>
@xpansive

This comment has been minimized.

Copy link
Owner Author

xpansive commented Feb 26, 2012

Saved 36 bytes by rewriting it the obvious way...

function(a,b){return a.slice(b%=a.length)+a.slice(0,b)}
@atk

This comment has been minimized.

Copy link

atk commented Mar 19, 2012

Save 5 bytes more by becoming even more obvious...
function(a){return a.split('').reverse().join('')}

@maettig

This comment has been minimized.

Copy link

maettig commented Mar 20, 2012

rotate is more like shift. reverse is a different function. If you want to do this with array functions it would be something like this:

function(a,b){for(a=a.split('');b--;)a.push(a.shift());return a.join('')}
@atk

This comment has been minimized.

Copy link

atk commented Mar 20, 2012

Sorry, missed that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.