Skip to content

Instantly share code, notes, and snippets.

@xpansive
Forked from 140bytes/LICENSE.txt
Created February 25, 2012 20:45
Show Gist options
  • Save xpansive/1910542 to your computer and use it in GitHub Desktop.
Save xpansive/1910542 to your computer and use it in GitHub Desktop.
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>
@atk
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