I am beginner and want to make my own function.
I want to hash the password by shifting every character by given x
positions and reverse to lowercase/uppercase.
I think the code below should return "EFGH7654" but it return 55 with no error message.
How can I fix it? Is it because of I put a function in a function?
Or I type wrong any thing?
function hashPassword(password, x) {
// password is a string, x is a number
// return a string
// (ex. password = 'ab1By', x = 3 so it should return "DE4eB")
function shift(text, s) {
result = "";
for (let i = 0; i < text.length; i++) {
let char = text[i];
if (char.toUpperCase(text[i])) {
let ch = String.fromCharCode((char.charCodeAt(0) + s - 65) % 26 + 65);
result += ch;
} else {
let ch = String.fromCharCode((char.charCodeAt(0) + s - 97) % 26 + 97);
result += ch;
}
}
return result;
}
function reversecase(x) {
var output = '';
for (var i = 0, len = x.length; i < len; i++) {
var character = x[i];
if (character == character.toLowerCase()) {
// The character is lowercase
output = output + character.toUpperCase();
} else {
// The character is uppercase
output = output + character.toLowerCase();
}
}
return output
}
var str = "";
var result = "";
var charcode = "";
for (var i = 0; i < password.length; i++) {
if (typeof password[i] === typeof str) {
char = shift(password[i], x)
charcode = reversecase(char)
result += charcode;
} else {
num = password[i] + x
number = num % 10
result += number.toString()
}
}
return result
};
console.log(hashPassword("abcd4321", 4))
There a quite some problems in your code.
The first problem here is not only the nesting, but the fact that you're defining the result variable in the outer function scope using the var keyword. Then you use (read/write) that variable in different places.
In function shift() (also in return statement)
In the outer function (also in return statement)
The thing you have to understand is, that you're referring to the same variable result every time. To ensure that your variables are scoped, i.e. are only valid within a block (if statement, function body, etc.), you should use the let or const keywords. This makes your code a lot safer.
The second problem are some assumptions you make regarding data types. If you have a string let s = "my string 123", the expression typeof s[x] === 'string' will be true for every x in s.
Another problem is the algorithm itself. The outer function hashPassword() iterates over all characters of the input string. Within that loop you call function shift(password[i], x), passing a single character. The first parameter of shift() is called text - and there is another for loop (which is confusing and does not make sense).
To make things short, please have a look at this simplified version:
function shift(char, x) {
let result;
const code = char.charCodeAt(0);
if (code >= 65 && code < 91) {
result = String.fromCharCode((code + x - 65) % 26 + 65);
}
else if (code >= 48 && code <= 57) {
result = String.fromCharCode((code + x - 48) % 10 + 48);
}
else {
result = String.fromCharCode((code + x - 97) % 26 + 97);
}
return result;
}
function reverseCase(character) {
if (character === character.toLowerCase()) {
return character.toUpperCase();
}
else {
return character.toLowerCase();
}
}
function hashPassword(password, x) {
let result = "";
for (let i = 0; i < password.length; i++) {
const char = shift(password[i], x);
result += reverseCase(char);
}
return result;
}
console.log(hashPassword("abcd4321", 4)); // Output: EFGH8765
Hi This is my first time using this website, I did do some research about how to convert lowercase letter to uppercase letter but still filles. The requirement is to check if "even", covert the even digit letter to different type(lower to upper or upper to lower). below is my code:
function question4(str,pos)
{ var newLetter;
var kkk=str;
if (pos='even')
{
for (var i=0;i<str.length;i=i+2)
{
if (str[i].toString()==str[i].toString().toUpperCase())
{
newLetter=str[i].toString().toLowerCase();
kkk[i]=newLetter;
}else
{
newLetter=str[i].toUpperCase();
kkk[i]=newLetter;
}
}
}else if (pos='odd')
for ( i=0;i<str.length;i=i+2)
{
if (str[i]===str[i].toLowerCase())
{
alert('3');
}else if (str[i]===str[i].toUpperCase())
{
alert('4');
}
}
return kkk;
}
the requirement is: Write a function to change the case of all the characters in string based on their position which matches the value of the pos parameter function. function (str, pos [even|odd]). Example ( (‘abCd’, ‘odd’) return Abcd)
Update: now I have make "odd" condition working, but "even "still is not working, can any one take a look why?
function question4(strr,pos) {
var result ;
var sum="";
var aaa;
for (var i = 0; i <= strr.length - 1; i = i + 1)
{
if (pos == "odd"&&i%2==0)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result = String.fromCharCode(aaa + 32);
} else
result = String.fromCharCode(aaa - 32);
}
else if (pos == "even"&&i%2==1)
{
if (aaa >= 65 && aaa <= 90 )
{
result= String.fromCharCode(aaa + 32);
} else
result = String.fromCharCode(aaa - 32);
}else result=strr[i];
sum+=result;
}
return sum;
}
To achieve this, you can construct a string by concating char by char:
function question4(strInput, pos) {
let str = ""; // The string to construct
if (!pos || (pos !== "even" && pos !== "odd")) { // Validating pos
throw "invalid pos";
}
for (var i=0;i<strInput.length;i++) // Looping on strInput
{
let huPos = i + 1;
if ((pos === "even" && huPos%2 == 1) ||
(pos === "odd" && huPos%2 == 0)) {
/* If we want switch odd and we are on even position or if we want switch even and we are on odd position, then we add the original char
*/
str += strInput[i];
}
else {
// In others case, we switch lower to upper and upper to lower
let char = strInput[i];
str += char == char.toUpperCase() ? char.toLowerCase() : char.toUpperCase();
}
}
return str;
}
console.log(question4('abCdef', "odd")); // Return "AbcdEf"
Associated bin
EDIT:
After seeing edit, i can see you want to do it without using toLower/UpperCase. As stated in comment i think it is a bad idea in js, but to experiment you can achieve this:
const reverser = {
"a": "a".charCodeAt(0),
"z": "z".charCodeAt(0),
"A": "A".charCodeAt(0),
"Z": "Z".charCodeAt(0),
};
const conversionValueToLower = reverser.a - reverser.A;
const conversionValueToUpper = reverser.A - reverser.a;
function reverseChar(char) {
var code = char.charCodeAt(0);
// If you want to go from upper to lower
if (code >= reverser.A && code <= reverser.Z) {
// Simply add the difference between lower and upper
return String.fromCharCode(code + conversionValueToLower);
} // Same logic here
else if (code >= reverser.a && code <= reverser.z) {
return String.fromCharCode(code + conversionValueToUpper);
}
/**
Or use if you want full digit
if (code <= 90 && code >= 65) {
return String.fromCharCode(code + 32);
}
else if (code >= 97 && code <= 122) {
return String.fromCharCode(code - 32);
}
**/
return char; // Other case return original char
}
function question4(strInput, pos) {
let str = "";
if (!pos || (pos !== "even" && pos !== "odd")) {
throw "invalid pos";
}
for (var i=0;i<strInput.length;i++)
{
let huPos = i + 1;
if ((pos === "even" && huPos%2 == 1) ||
(pos === "odd" && huPos%2 == 0)) {
str += strInput[i];
}
else {
str += reverseChar(strInput[i]);
}
}
return str;
}
console.log(question4('abCdef', "odd")); // return "AbcdEf"
Associated bin
Another way could be to code utils functions imitating toLower/UpperCase
I corrected your code in your answer aswell, without changing original logic
function question4(strr,pos) {
var result ;
var sum="";
var aaa;
for (var i = 0; i <= strr.length - 1; i = i + 1)
{
if (pos == "odd"&&i%2==0)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result = String.fromCharCode(aaa + 32);
} else if(aaa >=97&&aaa <=122)
{ result = String.fromCharCode(aaa - 32);}
else {result=strr[i];}
}
else if (pos == "even"&&i%2==1)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result= String.fromCharCode(aaa + 32);
} else if(aaa >=97&&aaa <=122)
{ result = String.fromCharCode(aaa - 32);}
else {result=strr[i];}
}else {result=strr[i];}
sum+=result;
}
return sum;
}
console.log(question4("abCd", "odd")) // return Abcd;
A simple solution for this question
// Function used to invert the letter case
const changeCase = c => {
if (c === c.toUpperCase()) return c.toLowerCase()
return c.toUpperCase()
}
const swapCaseConditional = (str, pos) => {
// Use split method to convert string into array and map the array
return str.split('').map((c, index) => {
if (pos === 'even') {
// if pos and index are even, change the letter case
if (index % 2) return changeCase(c)
return c
}
else {
// if pos and index are odd, change the letter case
if (!(index%2)) return changeCase(c)
return c
}
// Convert to string
}).join('')
}
console.log(swapCaseConditional('abCd', 'odd'))
I worked two nights and finally got it working. although not fully cover all the situations, but almost there.
function question4(strr,pos) {
var result ;
var sum="";
var aaa;
for (var i = 0; i <= strr.length - 1; i = i + 1)
{
if (pos == "odd"&&i%2==0)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result = String.fromCharCode(aaa + 32);
} else
result = String.fromCharCode(aaa - 32);
}
else if (pos == "even"&&i%2==1)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result= String.fromCharCode(aaa + 32);
} else if(aaa >=97&&aaa <=122)
{ result = String.fromCharCode(aaa - 32);}
else {result=strr[i];}
}else {result=strr[i];}
sum+=result;
}
return sum;
}
I am trying to write a program to solve the following problem in javascript (Written below this paragraph). I don't know why my code isn't working. Could someone help me? I'm new to javascript; this is a free code camp question.
"A common modern use is the ROT13 cipher, where the values of the letters are shifted by 13 places. Thus 'A' ↔ 'N', 'B' ↔ 'O' and so on.
Write a function which takes a ROT13 encoded string as input and returns a decoded string."
function rot13(str) { // LBH QVQ VG!
var string = "";
for(var i = 0; i < str.length; i++) {
var temp = str.charAt(i);
if(temp !== " " || temp!== "!" || temp!== "?") {
string += String.fromCharCode(13 + String.prototype.charCodeAt(temp));
} else {
string += temp;
}
}
return string;
}
// Change the inputs below to test
console.log(rot13("SERR PBQR PNZC")); //should decode to "FREE CODE CAMP"
Using modulus operator; makes the sentence uppercase;
function cipherRot13(str) {
str = str.toUpperCase();
return str.replace(/[A-Z]/g, rot13);
function rot13(correspondance) {
const charCode = correspondance.charCodeAt();
//A = 65, Z = 90
return String.fromCharCode(
((charCode + 13) <= 90) ? charCode + 13
: (charCode + 13) % 90 + 64
);
}
}
I have tried to make it simple and I earned FREE PIZZA!. Check my solution for this.
function rot13(str) {
var alphabets =['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'," ", "-", "_", ".", "&","?", "!", "#", "#", "/"];
var alphabets13 = ['N','O','P','Q','R','S','T','U','V','W','X','Y','Z','A','B','C','D','E','F','G','H','I','J','K','L','M', " ", "-", "_", ".", "&","?", "!", "#", "#", "/"];
var resultStr = [];
for(let i=0; i<str.length; i++){
for(let j =0; j<alphabets.length; j++){
if(str[i] === alphabets[j]){
resultStr.push(alphabets13[j]);
}
}
}
return resultStr.join("");
};
rot13("SERR CVMMN!");
You can build the algorithm for ROT13 directly... or just use a Caesar Cipher algorithm with the appropriate key.
The alternative that I'm proposing to your example is just a particular usage of a regular Caesar Cipher algorithm – a very simple form of encryption, in which each letter in the original message is shifted to the left or right by a certain number of positions.
To decrypt the message we simply shift back the letters the same number of positions.
Example:
JAVASCRIPT becomes MDYDVFULSW if we shift all letters by 3 positions
MDYDVFULSW turns back to JAVASCRIPT if we shift back all letters by 3 positions.
If after shifting a letter goes outside the range of letters, then the letter is wrapped around in alphabet. Example: Letter Z becomes C if is shifted by 3 positions.
This “wrap-around” effect means use of modulo. In mathematical terms, the above can be expressed as this:
En(x) = (x + n) mod 26
Dn(x) = (x – n) mod 26
Trying to implement this algorithm in JavaScript without the use of a proper modulo operator will produce either incorrect results or a very cryptic and difficult to understand code.
The biggest problem is that JavaScript doesn't contain a modulo operator. The % operator is just the reminder of the division - not modulo. However, it is pretty easy to implement modulo as a custom function:
// Implement modulo by replacing the negative operand
// with an equivalent positive operand that has the same wrap-around effect
function mod(n, p)
{
if ( n < 0 )
n = p - Math.abs(n) % p;
return n % p;
}
There are other ways of implementing modulo... if you are interested you can consult this article.
By using the mod function defined above, the code expresses the mathematical equation identically:
// Function will implement Caesar Cipher to
// encrypt / decrypt the msg by shifting the letters
// of the message acording to the key
function encrypt(msg, key)
{
var encMsg = "";
for(var i = 0; i < msg.length; i++)
{
var code = msg.charCodeAt(i);
// Encrypt only letters in 'A' ... 'Z' interval
if (code >= 65 && code <= 65 + 26 - 1)
{
code -= 65;
code = mod(code + key, 26);
code += 65;
}
encMsg += String.fromCharCode(code);
}
return encMsg;
}
To encode using ROT13 ... is now just a matter of choosing the appropriate key as indicated by algorithm name.
2020 TypeScript Version:
A shift argument must be given, but you can choose 13 for rot13 or any other number.
// TypeScript Type: Alphabet
type Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Helper Function: Caesar Cipher
export const caesarCipher = (string: string, shift: number) => {
// Alphabet
const alphabet: Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Encoded Text
let encodedText: string = '';
// Adjust Shift (Over 26 Characters)
if (shift > 26) {
// Assign Remainder As Shift
shift = shift % 26;
}
// Iterate Over Data
let i: number = 0;
while (i < string.length) {
// Valid Alphabet Characters
if (alphabet.indexOf(string[i]) !== -1) {
// Find Alphabet Index
const alphabetIndex: number = alphabet.indexOf((string[i]).toUpperCase());
// Alphabet Index Is In Alphabet Range
if (alphabet[alphabetIndex + shift]) {
// Append To String
encodedText += alphabet[alphabetIndex + shift];
}
// Alphabet Index Out Of Range (Adjust Alphabet By 26 Characters)
else {
// Append To String
encodedText += alphabet[alphabetIndex + shift - 26];
}
}
// Special Characters
else {
// Append To String
encodedText += string[i];
}
// Increase I
i++;
}
return encodedText;
};
Example #1:
console.log(caesarCipher('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 2));
Output:
CDEFGHIJKLMNOPQRSTUVWXYZAB
Example #2:
console.log(caesarCipher('GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK.', 26 + 13));
Output:
THE QUICK BROWN DOG JUMPED OVER THE LAZY FOX.
I just recently solved a caesar cipher algorithm problem that works similarly to your rot13, but will take any integer value as a shift parameter. One of the issues I notice with your code is you are already assigning temp as a number by assigning the charCode for the character at 'i'. This makes your conditional obsolete, since it will never identify the string values, since you're passing in a number value. Also, when you build the string, it should just be 'String.fromCharCode(13 + temp)'. I personally prefer the caesar cipher, since you can assign random shift parameters.
Here's an example of how I wrote it:
// s = string to encrypt, k = shift value
// s = 'SERR PBQR PNZC' and k = 13 will produce 'FREE CODE CAMP'
const caesarCipher = function(s, k) {
let result = '';
for (let i = 0; i < s.length; i++) {
let charCode = s[i].charCodeAt();
// check that charCode is a lowercase letter; automatically ignores non-letters
if (charCode > 96 && charCode < 123) {
charCode += k % 26 // makes it work with numbers greater than 26 to maintain correct shift
// if shift passes 'z', resets to 'a' to maintain looping shift
if (charCode > 122) {
charCode = (charCode - 122) + 96;
// same as previous, but checking shift doesn't pass 'a' when shifting negative numbers
} else if (charCode < 97) {
charCode = (charCode - 97) + 123;
}
}
if (charCode > 64 && charCode < 91) {
charCode += k % 26
if (charCode > 90) {
charCode = (charCode - 90) + 64;
} else if (charCode < 65) {
charCode = (charCode - 65) + 91;
}
}
result += String.fromCharCode(charCode);
}
return result
}
Note : This function will take care of alphabetic(a-z or A-Z) and all others will be ignored.
Considered points are
Handle negative number
Can take care of big number.
Handle special character, number and space will print as it is
sd
function caesarCipher(word, next) {
next = next % 26;
let res = "";
for (const letter of word) {
let letterCode = letter.charCodeAt(0);
if (letterCode >= 65 && letterCode <= 90) {
letterCode = letterCode + next;
if (letterCode > 90) {
letterCode = letterCode - 26;
} else if (letterCode < 65) {
letterCode = letterCode + 26;
}
} else if (letterCode >= 97 && letterCode <= 122) {
letterCode = letterCode + next;
if (letterCode > 122) {
letterCode = letterCode - 26;
} else if (letterCode < 97) {
letterCode = letterCode + 26;
}
}
res = res + String.fromCharCode(letterCode);
}
return res; }
console.log(caesarCipher("Zoo Keeper 666 %^&*(", 2));
console.log(caesarCipher("Big Car", -16));
Output
Bqq Mggrgt 666 %^&*(
Lsq Mkb
Here's a simple solution.
function caesar(str) {
str = str.split("")
str = str.map(char => {
let code = char.charCodeAt(0)
if( (code > 64 && code < 78) || (code > 96 && code < 110) )
code += 13
else if ( (code > 77 && code < 91) || (code > 109 && code < 123) )
code -= 13
return String.fromCharCode(code)
})
return str.join("")
}
const rot13 = (string) => {
// creating *letterBox* - string in alphabetic way
const letterBox = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// declaring *iter function* - that will pass through the text
const iter = (str, acc) => {
// if length of string is 0 (phrase is empty) => returning *accumulator*
if (str.length===0) { return acc; }
/* if is not an uppercase character => calling *function iter* by itself
with the new string minus first letter and adding to *accumulator*
without coding symbol */
if (! /^[A-Z]*$/.test(str[0])) {return iter(str.substring(1), acc+str[0]); };
// and now we loop through the uppercase letters (26 letters)
//checking their index in our *letterBox*
// if it's more that 13 , we add 13 , else we substract 13 and
// and of course... calling *iter function* with new string minus first character
// plus *accumumator*
for (let i=0; i<26;i++)
{
if ( (letterBox[i]===str[0]) && (i>12))
{ return iter(str.substring(1), acc + letterBox[i-13]); }
if ( (letterBox[i]===str[0])&& (i<13))
{ return iter(str.substring(1), acc + letterBox[i+13]); };
};
};
// calling *iter function* with the provided *string* and empty *accumulator*
return iter(string,'');
};
console.log(rot13('GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.'));
// THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.
passed with success test on codecamp.
also there is another version.. without iter function
const rot13=(str) =>
{
var alph= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let result ='';
while(str.length>0)
{
for (let i=0;i<=25;i++)
{
if ((alph[i]===str[0]) && (i>13)) {result = result + alph[i-13];};
if ((alph[i]===str[0]) && (i<13)) {result = result + alph[i+13] ;} ;
};
if (! /^[A-Z]*$/.test(str[0]) ) {result = result+ str[0];};
str=str.substring(1);
};
return result;
};
console.log(rot13('SERR YBIR?'));
// returns FREE LOVE?
I am recently in my first stage of developing a javascript library to simplify my daily programming requirements.
One of which is Encryption.
The library uses caesar encryption as of now.
You may download the minified version in the early development and use it in your html pages as:
d(window).loaded(function() {
/* *
* Tidy up the heading
* */
d("h1")
.background("#fafafa")
.color("orange");
/* *
* Encrypt all paragraphs and maximize the height so we view each paragraph separately
* */
d("p")
.encrypt(text = "", depth = 15)
.resize("60%", "50px");
/* *
* Show up the first paragraph element's html
* */
_.popUp("First Paragraph: <hr>" + dom("p").getText(), "", "purple")
})
/* *
* Show the inputed text in below snippet
* */
function showEncryptedText(){
d("#encrypted")
.encrypt(d("#plain").c[0].value, 15)
.background("#e8e8e8")
.resize("100%", "100px");
}
<!DOCTYPE HTML>
<html>
<head>
<title>Element Encryption</title>
<script type="text/javascript" src="https://raw.githubusercontent.com/Amin-Matola/domjs/master/dom-v1.0.0/dom.min.js"></script>
</head>
<body>
<h1>Javascript Encryption</h1>
<p>This is the first paragraph you may encrypt</p>
<p>This is another paragraph you may encrypt</p>
<p>You may encrypt this too</p>
<h2>You may even provide your text to be encrypted</h2>
<div id="encrypted">
</div>
<input type="text" id="plain" value="" name="mydata" oninput="showEncryptedText()"/>
</div>
<footer>
<!--- you may place your js here --->
<script type="text/javascript">
</script>
</body>
</html>
I just solved the caesar chipper problem using this algorithm.
function rot13(str) {
const rot13 = {
'N': "A",
'O': 'B',
'P': 'C',
'Q': 'D',
'R': 'E',
'S': 'F',
'T': 'G',
'U': 'H',
'V': 'I',
'W': 'J',
'X': 'K',
'Y': 'L',
'Z': 'M',
'A': 'N',
'B': 'O',
'C': 'P',
'D': 'Q',
'E': 'R',
'F': 'S',
'G': 'T',
'H': 'U',
'I': 'V',
'J': 'W',
'K': 'X',
'L': 'Y',
'M': 'Z'
}
const splitStr = str.split(' ').map(string => {
return string.split('').map(string => rot13[string] === undefined ? string : rot13[string]).join('');
}).join(' ');
return splitStr;
}
I see that people here have written lengthy codes. I have solved the problem using a simple solution.
function replacing(str){
let strAm = "ABCDEFGHIJKLMNOPQRSTUVWXYZ -_.&?!# #/";
let strNz = "NOPQRSTUVWXYZABCDEFGHIJKLM -_.&?!# #/";
let rot13 = '';
for (let i = 0; i < str.length; i++){
if (strAm.includes(str.charAt(i))){
rot13 += str.charAt(i).replace(str.charAt(i), strNz[strAm.indexOf(str.charAt(i))]);
}
}
return rot13;
}
console.log(replacing("GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT."));
This problem can be solved in many ways.
Below is the code using ASCII code of the characters in ths string and with two built in JavaScript functions i.e., charCodeAt() and String.fromCharCode()
function rot13(message) {
let cipherString = '';
let arr = [...message];
for (let i = 0; i < arr.length; i++) {
let asciiValue = arr[i].charCodeAt();
if (
(asciiValue >= 65 && asciiValue <= 90) ||
(asciiValue >= 97 && asciiValue <= 122)
) {
if (asciiValue >= 65 && asciiValue <= 90) {
if (asciiValue <= 77) {
asciiValue += 13;
} else {
asciiValue -= 13;
}
} else {
if (asciiValue <= 109) {
asciiValue += 13;
} else {
asciiValue -= 13;
}
}
cipherString += String.fromCharCode(asciiValue);
} else cipherString += arr[i];
}
return cipherString;
}
I wanted to post my way to do it in typestcript.
function caesarCipher(s: string, k: number): string {
//[ [ 'A', 65 ], [ 'Z', 90 ], [ 'a', 97 ], [ 'z', 122 ] ]
return [...s]
.map(l => (l.charCodeAt(0)))
.map(n => n >= 65 && n <= 90 ? ((n - 65 + k) % 26) + 65 : n)
.map(n => n >= 97 && n <= 122 ? ((n - 97 + k) % 26) + 97 : n)
.map(n => String.fromCharCode(n))
.join("")
}
Solution using for loop, in each iteration check if character is alphabet then decode it by subtracting 13 from it's ascii code, if decoded character is not alphabet (its ascii code is less than 65), then decode it by adding 13 to it.
function rot13(str) {
function isAlphabet(char) {
return String(char).match(/[A-Z]/);
}
const chars = str.split("");
for(let i = 0 ; i < chars.length; i++) {
const char = chars[i];
if(isAlphabet(char)) {
const decoded = String.fromCharCode(char.charCodeAt() - 13);
const decodedAlphabet = String.fromCharCode(char.charCodeAt() + 13);
chars[i] = isAlphabet(decoded)? decoded : decodedAlphabet;
}
}
return chars.join("")
}
Here is my approach - provide input and shift.
It maintains lower or upper case of original input and leave unprocessable letters in place:
ceasarCipher("Hello Stackoverflow!");
// Khoor Vwdfnryhuiorz!
function ceasarCipher(input: string, shift = 3) {
const letters = input.split("");
const anyLetter = /[a-z]/i;
return letters
.map((letter) => {
if (!anyLetter.test(letter)) return letter;
const upperLetter = letter.toUpperCase();
const wasOriginalUpper = letter === upperLetter;
const charCode = upperLetter.charCodeAt(0);
//A = 65, Z = 90
const maskedLetter = String.fromCharCode(
charCode + shift <= 90
? charCode + shift
: ((charCode + shift) % 90) + 64
);
if (wasOriginalUpper) {
return maskedLetter;
}
return maskedLetter.toLowerCase();
})
.join("");
}
Simple Implementation of Caesar's Cipher(From FREE CODE CAMP)
function rot13(str) {
const alpha="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let ans="";
for(let i=0;i<str.length; i++){
const char=str[i];
if(char===" " || char==="!" || char==="?" || char==="."){
ans+=char;
}
else{
const val=alpha.indexOf(str[i]);
const new_val=(val+13)%26;
ans+=alpha[new_val];
}
}
return ans;
}
console.log(rot13("SERR PBQR PNZC"));
While A + 13 may equal N, Z + 13 will not compute correctly.
I'm checking for integer values in node.js using IsNaN function.
Unexpectedly, this function validates the strings like 1E267146, 1E656716 , 914E6583 to be numbers, as these strings are exponential values. Any way to work around this? In actual scenario i wont get any exponential values.
ECMA6 defines Number.isInteger as follows:
Javascript
function isInteger(nVal) {
return typeof nVal === "number" && isFinite(nVal) && nVal > -9007199254740992 && nVal < 9007199254740992 && Math.floor(nVal) === nVal;
}
but this will also accept scientific notation
console.log(isInteger(1e6));
console.log(isInteger(+"1e6"));
jsfiddle
You need to be clear as to what your definitions/expectations are.
My guess is that you may want something like this, if you are testing strings and have no limits on the max or min integer.
Javascript
function isStringNumericalInteger(testValue) {
return typeof testValue === "string" && /^[\-+]?[1-9]{1}\d+$|^[\-+]?0$/.test(testValue);
}
console.log(isStringNumericalInteger("9007199254740991"));
console.log(isStringNumericalInteger("-123216848516878975616587987846516879844651654847"));
console.log(isStringNumericalInteger("1.1"));
console.log(isStringNumericalInteger("-1.1"));
console.log(isStringNumericalInteger("1e10"));
console.log(isStringNumericalInteger("010"));
console.log(isStringNumericalInteger("0x9"));
console.log(isStringNumericalInteger(""));
console.log(isStringNumericalInteger(" "));
console.log(isStringNumericalInteger());
console.log(isStringNumericalInteger(null));
console.log(isStringNumericalInteger([]));
console.log(isStringNumericalInteger({}));
Output
true
true
false
false
false
false
false
false
false
false
false
false
false
jsfiddle
If you want to bound the range to what javascript can represent numerically as an integer then you will need to add a test for && +testValue > -9007199254740992 && +testValue < 9007199254740992
If you don't like using RegExs, you can also accomplish this with a parser. Something like this:
Javascript
function isCharacterDigit(testCharacter) {
var charCode = testCharacter.charCodeAt(0);
return charCode >= 48 && testCharacter <= 57;
}
function isStringNumericalInteger(testValue) {
var start = 0,
character,
index,
length;
if (typeof testValue !== "string") {
return false;
}
character = testValue.charAt(start);
if (character === "+" || character === "-") {
start += 1;
character = testValue.charAt(start);
}
start += 1;
length = testValue.length;
if ((length > start && character === "0") || !isCharacterDigit(character)) {
return false;
}
for (index = start; index < length; index += 1) {
if (!isCharacterDigit(testValue.charAt(index))) {
return false;
}
}
return true;
}
jsfiddle
I would use something like below code to validate number input. First I parse the given value to float and then check isNaN().
var isNumber = function (obj) {
return !isNaN(parseFloat(obj)) && isFinite(obj);
};
I think this is what you need in your case (i hate regex because this is not very good for the performance but..)
http://jsbin.com/EQiBada/1/
var NMAX = Math.pow(2, 53);
function isNumeric(n) {
n = n < 0 ? n * -1 : n;
var r = /^\d+$/.test(n);
if (r === true)
{
return parseInt(n, 10) >= (NMAX * -1) + 1 && parseInt(n, 10) <= NMAX;
}
return false;
}
Minified
var NMAX = Math.pow(2, 53);
function isNumericMin(n) {
n = n < 0 ? n * -1 : n;
return /^\d+$/.test(n) === true ? parseInt(n, 10) >= (NMAX * -1) + 1 && parseInt(n, 10) <= NMAX : false;
}
var i = '1E267146'
if(isNaN(i) || !isFinite(i) !! i=="")
{
// do stuff
}
else
{
// do stuff
}