daily pastebin goal
31%
SHARE
TWEET

Untitled

a guest Jun 13th, 2018 64 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Shifts an alphabetic string (e.i. 'a' --> 'b')
  2. // The 'str' argument is the string to pass in
  3. // 'n' is the number of characters that should be shifted
  4. // Supports shifting either forwards or backwards any amount
  5. // Example:
  6. // Input: shift('Ebiil, Tloia!', 3);
  7. // Expected Output: "Hello, World!"
  8. // Takes into account capital letters, lowercase letters, ignores non-alphabetic characters
  9.  
  10. function shift(str, n) {
  11.     var shifted = '';
  12.     n %= 26;
  13.     for (var i = 0; i < str.length; i++) {
  14.         let code = str[i].charCodeAt();
  15.     let capital = (code > 64 && code < 91) ? true : false;
  16.     if (code < (capital?65:97) || code > (capital?90:122) || n == 0) {
  17.       shifted += str[i];
  18.       continue;
  19.     }
  20.     if (n > 0) {
  21.       if (code > (capital?90:122)-n) {
  22.             code = n + code - 26;
  23.         } else {
  24.             code += n;
  25.         }
  26.     } else {
  27.       if (code < (capital?65:97)-n) {
  28.             code = code + n + 26;
  29.         } else {
  30.             code += n;
  31.         }
  32.     }
  33.         shifted += String.fromCharCode(code);
  34.     }
  35.     return shifted;
  36. }
  37.  
  38. // Below is the same function in prototype form aka 'string'.shift(n) as opposed to shift('string', n)
  39.  
  40. String.prototype.shift = function(n) {
  41.   var shifted = '';
  42.   n %= 26;
  43.     for (var i = 0; i < this.length; i++) {
  44.         let code = this[i].charCodeAt();
  45.     let capital = (code > 64 && code < 91) ? true : false;
  46.     if (code < (capital?65:97) || code > (capital?90:122) || n == 0) {
  47.       shifted += this[i];
  48.       continue;
  49.     }
  50.     if (n > 0) {
  51.       if (code > (capital?90:122)-n) {
  52.             code = n + code - 26;
  53.         } else {
  54.             code += n;
  55.         }
  56.     } else {
  57.       if (code < (capital?65:97)-n) {
  58.             code = code + n + 26;
  59.         } else {
  60.             code += n;
  61.         }
  62.     }
  63.         shifted += String.fromCharCode(code);
  64.     }
  65.     return shifted;
  66. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top