Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Shifts an alphabetic string (e.i. 'a' --> 'b')
- // The 'str' argument is the string to pass in
- // 'n' is the number of characters that should be shifted
- // Supports shifting either forwards or backwards any amount
- // Example:
- // Input: shift('Ebiil, Tloia!', 3);
- // Expected Output: "Hello, World!"
- // Takes into account capital letters, lowercase letters, ignores non-alphabetic characters
- function shift(str, n) {
- var shifted = '';
- n %= 26;
- for (var i = 0; i < str.length; i++) {
- let code = str[i].charCodeAt();
- let capital = (code > 64 && code < 91) ? true : false;
- if (code < (capital?65:97) || code > (capital?90:122) || n == 0) {
- shifted += str[i];
- continue;
- }
- if (n > 0) {
- if (code > (capital?90:122)-n) {
- code = n + code - 26;
- } else {
- code += n;
- }
- } else {
- if (code < (capital?65:97)-n) {
- code = code + n + 26;
- } else {
- code += n;
- }
- }
- shifted += String.fromCharCode(code);
- }
- return shifted;
- }
- // Below is the same function in prototype form aka 'string'.shift(n) as opposed to shift('string', n)
- String.prototype.shift = function(n) {
- var shifted = '';
- n %= 26;
- for (var i = 0; i < this.length; i++) {
- let code = this[i].charCodeAt();
- let capital = (code > 64 && code < 91) ? true : false;
- if (code < (capital?65:97) || code > (capital?90:122) || n == 0) {
- shifted += this[i];
- continue;
- }
- if (n > 0) {
- if (code > (capital?90:122)-n) {
- code = n + code - 26;
- } else {
- code += n;
- }
- } else {
- if (code < (capital?65:97)-n) {
- code = code + n + 26;
- } else {
- code += n;
- }
- }
- shifted += String.fromCharCode(code);
- }
- return shifted;
- }
Add Comment
Please, Sign In to add comment