How to get unlimited characters in a personal encryption on Javascript - javascript

Recently, I have been working on an piece of code that encrypts letters and decrypts them as long as the user has the proper, custom key. I worked out how to do it, but for every letter I want to add, I have to put:
if ( map.hasOwnProperty(input[0]) )
{
var _1 = map[input[0]]
}
Then at the end:
var encrypted = (_1 + _2 + _3 + _4 + _5 + _6 + _7 + _8 + _9 + _10 + _11 + _12 + _13 + _14 + _15 + _16 + _17 + _18 + _19 + _20 + _21 + _22 + _23 + _24 + _25 + _26 + _27 + _28 + _29 + _30 + _31 + _32 + _33 + _34 + _35 + _36 + _37 + _38 + _39 + _40 + _41 + _42 + _43 + _44 + _45 + _46 + _47 + _48 + _49 + _50 + _51 + _52 + _53 + _54)
For however many letters I put in.
A simplified version of the code with only 3 letters is this:
var map = {
"a" : "A",
"b" : "B",
"c" : "C",
"d" : "D",
"e" : "E",
"f" : "F",
"g" : "G",
"h" : "H",
"i" : "I",
"j" : "J",
"k" : "K",
"l" : "L",
"m" : "M",
"n" : "N",
"o" : "O",
"p" : "P",
"q" : "Q",
"r" : "R",
"s" : "S",
"t" : "T",
"u" : "U",
"v" : "V",
"w" : "W",
"x" : "X",
"y" : "Y",
"z" : "Z",
" " : " "
}
function main()
{
var input = prompt("Enter a character!");
var encrypted = -1;
if ( map.hasOwnProperty(input[0]) )
{
var _1 = map[input[0]]
}
if ( map.hasOwnProperty(input[1]) )
{
var _2 = map[input[1]]
}
if ( map.hasOwnProperty(input[2]) )
{
var _3 = map[input[2]]
}
var encrypted = (_1 + _2 + _3)
document.write(encrypted);
}
main()
(The map is just for simplicity, as it is a little more complicated in the full code)
Is there a way to have access to as many letters as I want to simplify the code?

You can use a loop for this kind of thing. Here is an example:
var map = {" " : " "};
for(var i = 0; i < 25; i++){
map[String.fromCharCode(97 + i)] = String.fromCharCode(65 + i);
}
function main() {
var input = prompt("Enter a character!");
var encrypted = "";
for(var i = 0; i < input.length; i++){
if(map[input[i]]){
encrypted += map[input[i]];
}
}
document.write(encrypted);
}
main();

Related

js: hand generated text to next site

i use this js code to generate text:
let green, display, button, clock, end;
green = ["x", "t", "g", "l"];
display = ["l", "h", "r", "e"];
button = ["e", "D", "l", "w"];
clock = ["o", "b", "a.", "e"];
end = ["T", "g", "t", "w"];
function randGen() {
return Math.floor(Math.random() * 4);
}
function sentence() {
let rand1 = Math.floor(Math.random() * 4);
let content = clock[rand1] + " " + display[rand1] + " " + button[rand1] + " " + green[rand1] + " " + end[rand1];
document.getElementById('sentence').innerHTML = """ + content + """;
};
sentence();
and put it in html like this:
<button style="" onclick="sentence()">generate text<i class="fa fa-refresh" aria-hidden="true"></i></button>
<div class="container">
<p id="sentence"></p>
</div>
Now i want to use the generated text the user generates by hitting the "generate text"-button on another html-document. Is it possible? Do i need to safe this text anywhere before using it on another html-document?
thanks in advance
John
You can use localStorage to solve your problem.
Save your sentence to localStorage like this:
function sentence() {
let rand1 = Math.floor(Math.random() * 4);
let content = clock[rand1] + " " + display[rand1] + " " + button[rand1] + " " + green[rand1] + " " + end[rand1];
return content;
};
// Check browser support
if (typeof(Storage) !== "undefined") {
localStorage.setItem("sentence", sentence());
}
And get sentence value on another page like this:
<div id="result"></div>
<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
document.getElementById("result").innerHTML = localStorage.getItem("sentence");
} else {
document.getElementById("result").innerHTML = "Browser does not support Web Storage.";
}
</script>
Hopefully, it will help your problem. Please let me know if you have any issues.

"Document is missing (perhaps it was deleted?)" in reference to a document that was just created

My script creates a document, stores the document url in a cell on the spreadsheet, then another function opens said document using that url. I am getting the "Document is missing" error about 70% of the time I attempt to run it. Any ideas? the failure is on line 52.
function resultsDoc() {
var ssa = SpreadsheetApp;
var ss = ssa.getActiveSpreadsheet();
var sheets = ss.getSheets();
var ui = ssa.getUi();
var doca = DocumentApp;
var drive = DriveApp;
var template = "1uSCtqPwDYM-AtGAu3kzv3ZD0jdXnl12GxmdF_BDNb-M";
var source = doca.openById(template);
var resDocCopy = drive.getFileById(template).makeCopy('Tournament Results');
var resDocId = resDocCopy.getId();
var resDoc = doca.openById(resDocId);
var docBody = resDoc.getBody();
var resDocUrl = resDoc.getUrl();
sheets.shift();
for (var dis in sheets) {
var thisSheet = sheets[dis];
var letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "f"];
var disLetter = letters[dis];
var eventa = thisSheet.getName();
var aOne = thisSheet.getRange('B3').getValue() + " " + thisSheet.getRange('A3').getValue();
var aTwo = thisSheet.getRange('B4').getValue() + " " + thisSheet.getRange('A4').getValue();
var aThree = thisSheet.getRange('B5').getValue() + " " + thisSheet.getRange('A5').getValue();
var aFour = thisSheet.getRange('B6').getValue() + " " + thisSheet.getRange('A6').getValue();
var aFive = thisSheet.getRange('B7').getValue() + " " + thisSheet.getRange('A7').getValue();
var aSix = thisSheet.getRange('B8').getValue() + " " + thisSheet.getRange('A8').getValue();
docBody.replaceText('<<' + disLetter + '>>', eventa);
docBody.replaceText('<<' + disLetter + '1>>', aOne);
docBody.replaceText('<<' + disLetter + '2>>', aTwo);
docBody.replaceText('<<' + disLetter + '3>>', aThree);
docBody.replaceText('<<' + disLetter + '4>>', aFour);
docBody.replaceText('<<' + disLetter + '5>>', aFive);
docBody.replaceText('<<' + disLetter + '6>>', aSix);
}
ss.insertSheet("Links");
var linksSheet = ss.getSheetByName("Links");
linksSheet.getRange(1, 1).setValue("Link to results page:");
linksSheet.getRange(2, 1).setValue(resDocUrl);
Utilities.sleep(9000);
}
function sweepsDoc() {
var doca = DocumentApp;
var linksSheet = ss.getSheetByName("Links");
var resDocUrl = linksSheet.getRange(2, 1).getValue();
var resDoc = doca.openByUrl(resDocUrl);
var docBody = resDoc.getBody();
var sweepsSheet = ss.getSheetByName('Sweeps');
docBody.replaceText("<<sweeps1>>", sweepsSheet.getRange('B2').getValue());
docBody.replaceText("<<sweeps2>>", sweepsSheet.getRange('B3').getValue());
docBody.replaceText("<<sweeps3>>", sweepsSheet.getRange('B4').getValue());
}
Alright - so I figured out a "workaround" more than an actual solution. Instead of storing and accessing the document Url, I switched over to using the document's Id.
While I still don't understand why the Url causes it to lose track of the document, using the Id has 100% success rate over 20 attempts, while using the Url only had a 10% success rate over 20.
If you know what the problem with using the Url is, please let me know. If you're having the same problem, switch your code to use the doc id.
I'm not 100% sure, but I think not saving the document could be causing the problem.
Add the line below to the end of your code that builds the doc.
resDoc.saveAndClose();

Javascript letter selection doesn't work in Google Chrome

My javascript code display letters on the top of the grid . It doesn't display on Google Chrome .The main issue is , my array letterselection_datareturn_admindash.push(myvariable); doesn't collect the data at all so it passes the null data to letterselection function so it doesn't work. Here is the function and html code
function letterselection(data) {
var letters = ["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"];
$.each(letters, function (key, value) {
myNamete_admindash = 'ByLetter';
var appends = '<li><a onclick="' + myNamete_admindash + '(\'' + value.toUpperCase() + '\')" href="#' + value.toUpperCase() + '">' + value.toUpperCase() + '</a></li>';
$('ul.pagination').append(appends);
});
}
var letterselection_datareturn_admindash = new Array();
function getData(myvariable, obj, i) {
var deletedColumns = obj.length;
$.each(deletedColumns, function (index, deletedColumn) {
letterselection_datareturn_admindash.push(myvariable);
});
}
HTML
<div class="pagination">
<ul class="pagination"></ul>
</div>
The issue is resolved . Now it is working on multiple browsers
Here is the answer :
function getData(myvariable, obj, i) {
var deletedColumns = obj.length;
letterselection_datareturn_admindash.push(myvariable);
}
I refined my code by deleting this lineof the code $.each(deletedColumns, function (index, deletedColumn) {

Cannot read property of undefined - JavaScript

I have problem withe code geoloaction auto. When pressing the button, the current location has an error:
Uncaught TypeError: Cannot read property 'coords' of undefined
code:
var date = new Date();
var Today = date.getDay();
function loadWeather(cityCoords){
var latlng = cityCoords.coords.latitude + "," + cityCoords.coords.longitude;
var forecastURL = "https://api.forecast.io/forecast/3a6d5408bc15a469385cf59ee96c0205/" + latlng +"?lang=ar&si&raw";
$.ajax({
url: forecastURL,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
updateCurrentWeather(json);
weeklyForecast(json);
},
error: function(e) {
console.log(e.message);
}
});
}
function updateCurrentWeather (json) {
$("#current_temp").html(Math.round(json.currently.temperature) + "; C");
$("#current_summary").html ( " الحالة الجوية : "+ json.currently.summary) ;
$("#current_temp").attr("data-icon",icons[json.currently.icon]);
$("#current_windSpeed").html( " الرياح : "+json.currently.windSpeed);
}
function weeklyForecast (json) {
var Day = Today;
var outhtml;
for ( var i = 0; i <= 6; i++)
{
outhtml = "";
Day = Day + 1
//check if day is greater than number in week
if ( Day === 7) {
Day = 0;
}
//format html
outhtml = '<li><h3 class="icon" data-icon="' + icons[json.daily.data[i].icon] + ' ">' + days[Day];
outhtml = outhtml + (json.daily.data[i].summary);
outhtml = outhtml + ", العليا " + Math.round(json.daily.data[i].temperatureMax) + "° C ";
outhtml = outhtml + " , صغرى " + Math.round(json.daily.data[i].temperatureMin) + "° C ";
outhtml = outhtml + '</h3></li>';
//append new html li item to list view
$(".WeekForecast").append(outhtml);
}
}
function loadDefaultCity() {
loadCity("Baghdad");
}
function loadCity(city) {
$("#location").html(city);
if (city.toLowerCase() == "current location") {
if ( navigator.geolocation ) {
navigator.geolocation.getCurrentPosition(loadWeather, loadDefaultCity);
} else {
loadDefaultCity();
}
} else {
loadWeather(cities[city.toLowerCase()]);
}
}
another data javascript appears cities[city.toLowerCase()] is defined
var icons = {
"clear-day" : "B",
"clear-night" : "C",
"rain" : "R",
"snow" : "G",
"sleet" : "X",
"wind" : "S",
"fog" : "N",
"cloudy" : "Y",
"partly-cloudy-day" : "H",
"partly-cloudy-night" : "I",
};
var cities = {
"baghdad" : { coords : { latitude : "33.3333", longitude: "44.3833" }},
"current location" : ""
};
var days = {
"0" : "الاحد : ",
"1" : "االاثنين : ",
"2" : ": الثلاثاء",
"3" : "الاربعاء : ",
"4" : "الخميس : ",
"5" : "الجمعة : ",
"6" : "السبت : "
};
var hours = {
"0" : "1",
"1" : "2",
"2" : "3",
"3" : "4",
"4" : "5",
"5" : "6",
"6" : "7",
};

Recursion with Javascript on JSON data

So, I have this function.
function makeContent(jsonData) {
var aProperty,
containerType,
contentContainerName,
containerIdentifier,
containerComment,
theContent;
console.log("jsonData = ");
console.log(jsonData);
var madeContent;
for (aProperty in jsonData) {
console.log("Working on property " + aProperty);
console.log("With value of ");
console.log(jsonData[aProperty]);
switch (aProperty) {
case "containerType": {
containerType = jsonData[aProperty];
break;
}
case "contentContainerName": {
contentContainerName = jsonData[aProperty];
break;
}
case "containerComment": {
containerComment = jsonData[aProperty];
break;
}
case "containerIdentifier": {
containerIdentifier = jsonData[aProperty];
break;
}
case "itemContent": {
theContent = jsonData[aProperty];
break;
}
}
}
if (typeof theContent !== 'undefined') {
console.log("theContent =");
console.log(theContent);
if (theContent.hasOwnProperty) {
if (madeContent != 'undefined') {
madeContent = makeContent(theContent);
madeContent = "<" + containerType + " " + containerIdentifier + "=\"" + contentContainerName + "\">" + madeContent + "</" + containerType + ">" + containerComment;
}
} else {
madeContent = "<" + containerType + " " + containerIdentifier + "=\"" + contentContainerName + "\">" + theContent + "</" + containerType + ">" + containerComment
console.log(madeContent);
console.log("Else statement");
}
}
return madeContent;
}
My trouble doesn't start until after the recursive call. For some reason after I call the makeContent() again in a recursive way, in the for loop to go through the properties in the object, I get 0 for the aProperty.
The JSON Data:
{
"contentContainerName" : "footer-bgcontent",
"containerType" : "div",
"containerIdentifier" : "id",
"containerComment" : "<!-- End #footer-bgcontent-->",
"itemContent" : [
{
"contentContainerName" : "footer",
"containerType" : "div",
"containerIdentifier" : "id",
"contentComment" : "<!-- End #footer -->",
"itemContent" : [
{
"contentContainerName" : "footerLink",
"containerType" : "a",
"containerIdentifier" : "id",
"contentTag" : ""
},
{
"contentContainerName" : "footerContent",
"containerType" : "div",
"containerIdentifier" : "id",
"contentTag" : "<div id=\"footerContent\"></div><!-- End #footerContent-->",
"itemContent" : [
{
"contentContainerName" : "createdBy",
"containerType" : "p",
"containerIdentifier" : "id",
"contentTag" : "<p id=\"createdBy\"></p>",
"itemContent" : "Created by: Patrick McAvoy"
},
{
"contentContainerName" : "lastModified",
"containerType" : "p",
"containerIdentifier" : "id",
"contentTag" : "<p id=\"lastModified\"></p>",
"itemContent" : "Last Modified: "
},
{
"contentContainerName" : "copyright",
"containerType" : "p",
"containerIdentifier" : "id",
"contentTag" : "<p id=\"copright\"></p>",
"itemContent" : "Copright"
}
]
}
]
}
]
}
Then the output
jsonData =
footer.js:51
Object
footer.js:55Working on property contentContainerName
footer.js:56With value of
footer.js:57footer-bgcontent
footer.js:55Working on property containerType
footer.js:56With value of
footer.js:57div
footer.js:55Working on property containerIdentifier
footer.js:56With value of
footer.js:57id
footer.js:55Working on property containerComment
footer.js:56With value of
footer.js:57<!-- End #footer-bgcontent-->
footer.js:55Working on property itemContent
footer.js:56With value of
footer.js:57[
Object
]
footer.js:83theContent =
footer.js:84[
Object
]
footer.js:50jsonData =
footer.js:51[
Object
]
footer.js:55Working on property 0
footer.js:56With value of
footer.js:57
Object
footer.js:38Made content:
footer.js:39<div id="footer-bgcontent">undefined</div><!-- End #footer-bgcontent-->
I'm unsure if this is causing your problem, but this line is wrong:
if (theContent.hasOwnProperty)
.hasOwnProperty is a method of every object/type in JS, so the test above is always true and so your code will always recurse, even if .itemContent is a string.
In any event, the code is unnecessarily complicated - there's no need to iterate through all the properties and test each key - just assign them directly to the required variables!
I believe the below code replicates what you're trying to do and is much shorter!
function makeContent(data) {
var type = data.containerType || 'div',
name = data.contentContainerName || '',
id = data.containerIdentifier || 'id',
comment = data.containerComment || '',
content = data.itemContent || '';
if (Array.isArray(content)) {
content = content.map(makeContent).join('');
}
return '<' + type + ' ' + id + '="' + name + '">' + content +
'</' + type + '>' + comment;
}
where the || 'foo' ensures the strings are assigned default values if not specified.
See http://jsfiddle.net/alnitak/rmTTg/ - NB: this code does nothing with the contentTag proeprty which is also unused in your own code.

Categories

Resources