Stuck on Converting a JS function to Perl - javascript

Im trying to convert this: (JS function) to Perl.
Decrypt3 = function (strIn, strKey) {
var strOut = new String();
var lenIn = strIn.length;
var lenKey = strKey.length;
var i = 0;
var numIn;
var numKey;
while (i < lenIn) {
numIn = parseInt(strIn.substr(i, 2), 32);
numKey = strKey.charCodeAt(i / 2 % lenKey);
strOut += String.fromCharCode(numIn - numKey);
i += 2;
}
return strOut;
};
This is as far as I have come:
Im not sure how to the strOut and correct NumKey.
while (<>) {
chomp;
print Decrypt3($_, $key),"\n";
}
sub Decrypt3 {
my #str_in = unpack 'C*', shift;
my #str_key = unpack 'C*', shift;
my #str_out;
for my $i (0 .. $str_in) {
my $numin = int[$str_in[ord[$i 2], 32]
my $sum = $str_in[$i] + $str_key[$i / 2% #str_key];

use List::Util 1.29 qw( pairmap );
my #base32_syms = (0..9, 'a'..'v');
my %base32_sym_vals =
map {
lc($base32_syms[$_]) => $_,
uc($base32_syms[$_]) => $_,
}
0..$#base32_syms;
sub decrypt3 {
my #cypher =
pairmap { $base32_sym_vals{$a} * 32 + $base32_sym_vals{$b} }
split(//, shift);
my #key = unpack('C*', shift);
return
join ' ',
map { chr($cypher[$_] - $key[ $_ % #key ]) }
0..$#cypher;
}

Related

Javascript object that takes another object's property as parameter changes it somehow

I've been working on a Math Parser project. I'm almost finished but I encountered a problem that I couldn't find the reason for it.
I've got 3 javascript files:
main.js
var button1 = document.getElementById("button");
var text1 = document.getElementById("text");
var output = document.getElementById("result");
button1.addEventListener("click", function(){
var textInput = text1.value;
var cleared = new clearingUnwantedCharacters(textInput);
var marked = new subgroupMarking(cleared.output);
var prioritizedList = new subgroupPrioritization(marked.parenGroups);
for(var i = 0; i <= 360; i++){
var splittedPieces = new splittingOperators(prioritizedList.prioritizedGroups);
var calculatedPieces = new calculatePieces(splittedPieces.seperatedPieces, i, true);
console.log(calculatedPieces.result);
}
});
objects.js
function clearingUnwantedCharacters(inputText){
this.output = inputText;
this.output = this.output.replace(/\s+/g, '');
this.output = this.output.toLowerCase();
}
function subgroupMarking(inputText){
this.parenGroups = [inputText];
this.locLeftParen = markChar(this.parenGroups[0], "(");
this.locRigthParen = markChar(this.parenGroups[0], ")");
for(var i = this.locLeftParen.length-1; i >= 0; i--){
var leftParen = this.locLeftParen[i];
var rightParen = this.locRigthParen.find(function(res){return res > leftParen});
this.parenGroups[i+1] = this.parenGroups[0].substring(leftParen+1, rightParen);
this.parenGroups[0] = changeAt(this.parenGroups[0], leftParen, rightParen+1, "{_"+(i+1)+"}");
this.locLeftParen = markChar(this.parenGroups[0], "(");
this.locRigthParen = markChar(this.parenGroups[0], ")");
}
}
function subgroupPrioritization(subgroupList){
var withParenGroup = [];
var withoutParenGroup = [];
for(var i = 0; i < subgroupList.length; i++){
var content = subgroupList[i].toString();
var hasParenGroup = content.search(/{_\d+}/g);
if(hasParenGroup == -1){
withoutParenGroup.push(content);
}else{
withParenGroup.push(content);
}
}
this.prioritizedGroups = withParenGroup.concat(withoutParenGroup);
}
function splittingOperators(prioritizedGroupList){
this.seperatedPieces = [];
for(var i = prioritizedGroupList.length-1; i >= 0; i--){
var pieces = prioritizedGroupList[i].split(/(\+|\*|\/|\^|\b(?=-)|(?<=})(?=-))/g);
for(var k = 0; k < pieces.length; k++){
if(pieces[k] == ""){
pieces[k] = "+";
}
}
this.seperatedPieces.unshift(pieces);
}
}
function calculatePieces(pieceList, x, degreeOption){
this.result = pieceList;
for(var i = this.result.length-1; i >= 0; i--){ // ["34", "+", "2{_2}"]
for(var k = 0; k < this.result[i].length; k++){ // 34, +, 2{_2}
var specialFlag = false;
var totalMultiplication = (countChar(this.result[i][k], "-")%2 == 0) ? 1 : -1;
var has = {
x : this.result[i][k].includes("x"),
subgroup : (this.result[i][k].search(/{_\d+}/g) != -1),
logarithm : this.result[i][k].includes("log"),
trigonometry : (this.result[i][k].includes("sin") || this.result[i][k].includes("cos") || this.result[i][k].includes("tan") || this.result[i][k].includes("cot"))
};
if(has.trigonometry){
specialFlag = true;
var trigSubgroupIndexes = [];
var trigTypes = [];
var trigsMultiplied = 1;
this.result[i][k] = this.result[i][k].replace(/(?:arc)?(sin|cos|tan|cot){_(\d+)}/g, function(match, type, index){
trigSubgroupIndexes.push(parseInt(index));
if(match.includes("arc")){
trigTypes.push([true, type]);
}else{
trigTypes.push([false, type]);
}
return " ";
});
for(var l = 0; l < trigTypes.length; l++){
var inverseness = trigTypes[l][0];
var type = trigTypes[l][1];
var parameter = (degreeOption) ? convertToRadian(parseFloat(this.result[trigSubgroupIndexes[l]])) : parseFloat(this.result[trigSubgroupIndexes[l]]);
var result;
if(inverseness){
switch(type){
case "sin":
result = Math.asin(parameter);
break;case "cos":
result = Math.acos(parameter);
break;case "tan":
result = Math.atan(parameter);
break;case "cot":
result = 1 / Math.atan(parameter);
break;
}
}else{
switch(type){
case "sin":
result = Math.sin(parameter);
break;case "cos":
result = Math.cos(parameter);
break;case "tan":
result = Math.tan(parameter);
break;case "cot":
result = 1 / Math.tan(parameter);
break;
}
}
trigsMultiplied *= result;
}
totalMultiplication *= trigsMultiplied;
}
if(has.logarithm){
specialFlag = true;
var logSubgroupIndexes = [];
var logsMultiplied = 1;
this.result[i][k] = this.result[i][k].replace(/log{_(\d+)}{_(\d+)}/g, function(match, firstIndex, secondIndex){
logSubgroupIndexes.push([parseInt(firstIndex), parseInt(secondIndex)]);
return " ";
});
for(var l = 0; l < logSubgroupIndexes.length; l++){
var base = this.result[logSubgroupIndexes[l][0]];
var power = this.result[logSubgroupIndexes[l][1]];
logsMultiplied *= (Math.log(power) / Math.log(base));
}
totalMultiplication *= logsMultiplied;
}
if(has.subgroup){
specialFlag = true;
var subgroupIndexes = [];
var groupsMultiplied = 1;
this.result[i][k] = this.result[i][k].replace(/{_(\d+)}/g, function(match, index){
subgroupIndexes.push(parseInt(index));
return " ";
});
for(var l = 0; l < subgroupIndexes.length; l++){
groupsMultiplied *= this.result[subgroupIndexes[l]];
}
totalMultiplication *= groupsMultiplied;
}
if(has.x){
specialFlag = true;
var powerX = countChar(this.result[i][k], "x");
this.result[i][k] = this.result[i][k].replace("x", " ");
totalMultiplication *= Math.pow(x, powerX);
}
if(specialFlag == true){
var factors = this.result[i][k].match(/\d+/g);
if(factors !== null){
for(var l = 0; l < factors.length; l++){
totalMultiplication *= parseFloat(factors[l]);
}
}
if(!isFinite(totalMultiplication) || checkNum(this.result[i][k]) || this.result[i][k].includes("(") || this.result[i][k].includes(")")){
this.result[i][k] = NaN;
}else{
this.result[i][k] = totalMultiplication;
}
}
}
var operators = ["^","*","/","+","-"];
for(var k = 0; k < operators.length; k++){
var search = this.result[i].indexOf(operators[k]);
while(search != -1){
switch(operators[k]){
case "+":
this.result[i].splice(search-1, 3, checkParse(this.result[i][search-1]) + checkParse(this.result[i][search+1]));
break;case "-":
this.result[i].splice(search-1, 3, checkParse(this.result[i][search-1]) - checkParse(this.result[i][search+1]));
break;case "*":
this.result[i].splice(search-1, 3, checkParse(this.result[i][search-1]) * checkParse(this.result[i][search+1]));
break;case "/":
this.result[i].splice(search-1, 3, checkParse(this.result[i][search-1]) / checkParse(this.result[i][search+1]));
break;case "^":
this.result[i].splice(search-1, 3, Math.pow(checkParse(this.result[i][search-1]) , checkParse(this.result[i][search+1])));
break;
}
if(this.result[i].indexOf(operators[k], search) == -1){
break;
}else{
search = this.result[i].indexOf(operators[k], search);
}
}
}
}
if(isNaN(this.result[0][0])){
this.result = "An error has occured, please make sure the parameters are correct.";
}else{
this.result = this.result[0][0];
}
}
functions.js
function countChar(str, character){
return str.toString().split(character).length-1;
}
function markChar(str, character){
var charCount = str.split(character).length;
var result = [];
for(var i = 0; i < charCount - 1; i++){
if(result.length == 0){
result.push(str.indexOf(character));
}else{
result.push(str.indexOf(character, result[i-1] + 1));
}
}
return result;
}
function changeAt(str, startingIndex, endingIndex, replacement){ // Returns the given string with the part between startingIndex and endingIndex replaced with replacement.
return str.substring(0, startingIndex) + replacement + str.substring(endingIndex, str.length);
}
function checkParse(str){
if(/[a-z]/.test(str) || countChar(str, ".") > 1){
return NaN;
}else{
return parseFloat(str);
}
}
function checkNum(str){
return (/[a-z]/.test(str) || countChar(str, ".") > 1);
}
function convertToRadian(degrees) {
return degrees * Math.PI / 180;
}
It works as intended when done like above. It puts values to x according to the range specified in the for loop in main.js and console.logs the results. But I don't want to create splittingOperators object everytime I recalculate with another x value. It's unnecessary since the actual formula stays the same.
var button1 = document.getElementById("button");
var text1 = document.getElementById("text");
var output = document.getElementById("result");
button1.addEventListener("click", function(){
var textInput = text1.value;
var cleared = new clearingUnwantedCharacters(textInput);
var marked = new subgroupMarking(cleared.output);
var prioritizedList = new subgroupPrioritization(marked.parenGroups);
var splittedPieces = new splittingOperators(prioritizedList.prioritizedGroups);
for(var i = 0; i <= 360; i++){
var calculatedPieces = new calculatePieces(splittedPieces.seperatedPieces, i, true);
console.log(calculatedPieces.result);
}
});
When I put the object creation outside of the for loop, it calculates and logs the first x value, but it gives
Uncaught TypeError: this.result[i][k].includes is not a function
as error after that. I suspect it's because it changes splittedPieces.seperatedPieces when it shouldn't. I couldn't find any reason for it to do that or maybe I am missing something.

Decode http cache into normal html page

I am trying to convert this http cache into a normal html page so I can see the content.
Here is the http cache I am trying to convert: http://mediapreset.com/http-cache.log
There is this site that can help with converting http cache page into a normal html page, but their service is not working:
http://www.sensefulsolutions.com/2012/01/viewing-chrome-cache-easy-way.html
They do however provide this function:
(function() {
var preTags = document.getElementsByTagName('pre');
var preWithHeaderInfo = preTags[0];
var preWithContent = preTags[2];
var lines = preWithContent.textContent.split('\n');
// get data about the formatting (changes between different versions of chrome)
var rgx = /^(0{8}:\s+)([0-9a-f]{2}\s+)[0-9a-f]{2}/m;
var match = rgx.exec(lines[0]);
var text = '';
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
var firstIndex = match[1].length; // first index of the chars to match (e.g. where a '84' would start)
var indexJump = match[2].length; // how much space is between each set of numbers
var totalCharsPerLine = 16;
index = firstIndex;
for (var j = 0; j < totalCharsPerLine; j++) {
var hexValAsStr = line.substr(index, 2);
if (hexValAsStr == ' ') {
// no more chars
break;
}
var asciiVal = parseInt(hexValAsStr, 16);
text += String.fromCharCode(asciiVal);
index += indexJump;
}
}
var headerText = preWithHeaderInfo.textContent;
var elToInsertBefore = document.body.childNodes[0];
var insertedDiv = document.createElement("div");
document.body.insertBefore(insertedDiv, elToInsertBefore);
// find the filename
var nodes = [document.body];
var filepath = '';
while (true) {
var node = nodes.pop();
if (node.hasChildNodes()) {
var children = node.childNodes;
for (var i = children.length - 1; i >= 0; i--) {
nodes.push(children[i]);
}
}
if (node.nodeType === Node.TEXT_NODE && /\S/.test(node.nodeValue)) {
// 1st depth-first text node (with non-whitespace chars) found
filepath = node.nodeValue;
break;
}
}
outputResults(insertedDiv, convertToBase64(text), filepath, headerText);
insertedDiv.appendChild(document.createElement('hr'));
function outputResults(parentElement, fileContents, fileUrl, headerText) {
// last updated 1/27/12
var rgx = /.+\/([^\/]+)/;
var filename = rgx.exec(fileUrl)[1];
// get the content type
rgx = /content-type: (.+)/i;
var match = rgx.exec(headerText);
var contentTypeFound = match != null;
var contentType = "text/plain";
if (contentTypeFound) {
contentType = match[1];
}
var dataUri = "data:" + contentType + ";base64," + fileContents;
// check for gzipped file
var gZipRgx = /content-encoding: gzip/i;
if (gZipRgx.test(headerText)) {
filename += '.gz';
}
// check for image
var imageRgx = /image/i;
var isImage = imageRgx.test(contentType);
// create link
var aTag = document.createElement('a');
aTag.textContent = "Left-click to download the cached file";
aTag.setAttribute('href', dataUri);
aTag.setAttribute('download', filename);
parentElement.appendChild(aTag);
parentElement.appendChild(document.createElement('br'));
// create image
if (isImage) {
var imgTag = document.createElement('img');
imgTag.setAttribute("src", dataUri);
parentElement.appendChild(imgTag);
parentElement.appendChild(document.createElement('br'));
}
// create warning
if (!contentTypeFound) {
var pTag = document.createElement('p');
pTag.textContent = "WARNING: the type of file was not found in the headers... defaulting to text file.";
parentElement.appendChild(pTag);
}
}
function getBase64Char(base64Value) {
if (base64Value < 0) {
throw "Invalid number: " + base64Value;
} else if (base64Value <= 25) {
// A-Z
return String.fromCharCode(base64Value + "A".charCodeAt(0));
} else if (base64Value <= 51) {
// a-z
base64Value -= 26; // a
return String.fromCharCode(base64Value + "a".charCodeAt(0));
} else if (base64Value <= 61) {
// 0-9
base64Value -= 52; // 0
return String.fromCharCode(base64Value + "0".charCodeAt(0));
} else if (base64Value <= 62) {
return '+';
} else if (base64Value <= 63) {
return '/';
} else {
throw "Invalid number: " + base64Value;
}
}
function convertToBase64(input) {
// http://en.wikipedia.org/wiki/Base64#Example
var remainingBits;
var result = "";
var additionalCharsNeeded = 0;
var charIndex = -1;
var charAsciiValue;
var advanceToNextChar = function() {
charIndex++;
charAsciiValue = input.charCodeAt(charIndex);
return charIndex < input.length;
};
while (true) {
var base64Char;
// handle 1st char
if (!advanceToNextChar()) break;
base64Char = charAsciiValue >>> 2;
remainingBits = charAsciiValue & 3; // 0000 0011
result += getBase64Char(base64Char); // 1st char
additionalCharsNeeded = 3;
// handle 2nd char
if (!advanceToNextChar()) break;
base64Char = (remainingBits << 4) | (charAsciiValue >>> 4);
remainingBits = charAsciiValue & 15; // 0000 1111
result += getBase64Char(base64Char); // 2nd char
additionalCharsNeeded = 2;
// handle 3rd char
if (!advanceToNextChar()) break;
base64Char = (remainingBits << 2) | (charAsciiValue >>> 6);
result += getBase64Char(base64Char); // 3rd char
remainingBits = charAsciiValue & 63; // 0011 1111
result += getBase64Char(remainingBits); // 4th char
additionalCharsNeeded = 0;
}
// there may be an additional 2-3 chars that need to be added
if (additionalCharsNeeded == 2) {
remainingBits = remainingBits << 2; // 4 extra bits
result += getBase64Char(remainingBits) + "=";
} else if (additionalCharsNeeded == 3) {
remainingBits = remainingBits << 4; // 2 extra bits
result += getBase64Char(remainingBits) + "==";
} else if (additionalCharsNeeded != 0) {
throw "Unhandled number of additional chars needed: " + additionalCharsNeeded;
}
return result;
}
})()
How to use the function above to carry out the http cache conversion?
Here is the fiddle I'm working on: https://jsfiddle.net/emporio/9jdw8r68/2/
Here's a modified version that outputs ungzipped data to console:
(function convertCache() {
var preTags = document.querySelectorAll('script[type="http-cache"]');
var preWithHeaderInfo = preTags[0];
var preWithContent = preTags[1];
var lines = preWithContent.textContent.split('\n');
// get data about the formatting (changes between different versions of chrome)
var rgx = /^(0{8}:\s+)([0-9a-f]{2}\s+)[0-9a-f]{2}/m;
var match = rgx.exec(lines[0]);
var text = '';
var data = [];
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
var firstIndex = match[1].length; // first index of the chars to match (e.g. where a '84' would start)
var indexJump = match[2].length; // how much space is between each set of numbers
var totalCharsPerLine = 16;
index = firstIndex;
for (var j = 0; j < totalCharsPerLine; j++) {
var hexValAsStr = line.substr(index, 2);
if (hexValAsStr == ' ') {
// no more chars
break;
}
var asciiVal = parseInt(hexValAsStr, 16);
data.push(asciiVal);
text += String.fromCharCode(asciiVal);
index += indexJump;
}
}
var headerText = preWithHeaderInfo.textContent;
var elToInsertBefore = document.body.childNodes[0];
var insertedDiv = document.createElement("div");
document.body.insertBefore(insertedDiv, elToInsertBefore);
// find the filename
var nodes = [document.body];
var filepath = '';
while (true) {
var node = nodes.pop();
if (node.hasChildNodes()) {
var children = node.childNodes;
for (var i = children.length - 1; i >= 0; i--) {
nodes.push(children[i]);
}
}
if (node.nodeType === Node.TEXT_NODE && /\S/.test(node.nodeValue)) {
// 1st depth-first text node (with non-whitespace chars) found
filepath = node.nodeValue;
break;
}
}
var gZipRgx = /content-encoding: gzip/i;
if (gZipRgx.test(headerText)) {
var binData = new Uint8Array(data);
var data = pako.ungzip(binData);
var strData = String.fromCharCode.apply(null, new Uint8Array(data));
console.log(strData);
}
outputResults(insertedDiv, convertToBase64(text), filepath, headerText);
insertedDiv.appendChild(document.createElement('hr'));
function outputResults(parentElement, fileContents, fileUrl, headerText) {
// last updated 1/27/12
var rgx = /.+\/([^\/]+)/;
var filename = rgx.exec(fileUrl)[1];
// get the content type
rgx = /content-type: (.+)/i;
var match = rgx.exec(headerText);
var contentTypeFound = match != null;
var contentType = "text/plain";
if (contentTypeFound) {
contentType = match[1];
}
var dataUri = "data:" + contentType + ";base64," + fileContents;
// check for gzipped file
var gZipRgx = /content-encoding: gzip/i;
if (gZipRgx.test(headerText)) {
filename += '.gz';
}
// check for image
var imageRgx = /image/i;
var isImage = imageRgx.test(contentType);
// create link
var aTag = document.createElement('a');
aTag.textContent = "Left-click to download the cached file";
aTag.setAttribute('href', dataUri);
aTag.setAttribute('download', filename);
parentElement.appendChild(aTag);
parentElement.appendChild(document.createElement('br'));
// create image
if (isImage) {
var imgTag = document.createElement('img');
imgTag.setAttribute("src", dataUri);
parentElement.appendChild(imgTag);
parentElement.appendChild(document.createElement('br'));
}
// create warning
if (!contentTypeFound) {
var pTag = document.createElement('p');
pTag.textContent = "WARNING: the type of file was not found in the headers... defaulting to text file.";
parentElement.appendChild(pTag);
}
}
function getBase64Char(base64Value) {
if (base64Value < 0) {
throw "Invalid number: " + base64Value;
} else if (base64Value <= 25) {
// A-Z
return String.fromCharCode(base64Value + "A".charCodeAt(0));
} else if (base64Value <= 51) {
// a-z
base64Value -= 26; // a
return String.fromCharCode(base64Value + "a".charCodeAt(0));
} else if (base64Value <= 61) {
// 0-9
base64Value -= 52; // 0
return String.fromCharCode(base64Value + "0".charCodeAt(0));
} else if (base64Value <= 62) {
return '+';
} else if (base64Value <= 63) {
return '/';
} else {
throw "Invalid number: " + base64Value;
}
}
function convertToBase64(input) {
// http://en.wikipedia.org/wiki/Base64#Example
var remainingBits;
var result = "";
var additionalCharsNeeded = 0;
var charIndex = -1;
var charAsciiValue;
var advanceToNextChar = function() {
charIndex++;
charAsciiValue = input.charCodeAt(charIndex);
return charIndex < input.length;
};
while (true) {
var base64Char;
// handle 1st char
if (!advanceToNextChar()) break;
base64Char = charAsciiValue >>> 2;
remainingBits = charAsciiValue & 3; // 0000 0011
result += getBase64Char(base64Char); // 1st char
additionalCharsNeeded = 3;
// handle 2nd char
if (!advanceToNextChar()) break;
base64Char = (remainingBits << 4) | (charAsciiValue >>> 4);
remainingBits = charAsciiValue & 15; // 0000 1111
result += getBase64Char(base64Char); // 2nd char
additionalCharsNeeded = 2;
// handle 3rd char
if (!advanceToNextChar()) break;
base64Char = (remainingBits << 2) | (charAsciiValue >>> 6);
result += getBase64Char(base64Char); // 3rd char
remainingBits = charAsciiValue & 63; // 0011 1111
result += getBase64Char(remainingBits); // 4th char
additionalCharsNeeded = 0;
}
// there may be an additional 2-3 chars that need to be added
if (additionalCharsNeeded == 2) {
remainingBits = remainingBits << 2; // 4 extra bits
result += getBase64Char(remainingBits) + "=";
} else if (additionalCharsNeeded == 3) {
remainingBits = remainingBits << 4; // 2 extra bits
result += getBase64Char(remainingBits) + "==";
} else if (additionalCharsNeeded != 0) {
throw "Unhandled number of additional chars needed: " + additionalCharsNeeded;
}
return result;
}
})()
https://jsfiddle.net/9jdw8r68/6/
Data from chrome://cache info has to be split into two separate script tags (each with type="http-cache" attribute). When you open cache of specific URL and check page source code, you will see three pre tags there.
copy content of first pre into first script type="http-cache" tag
ignore second pre tag
copy content of third pre into second script type="http-cache" tag
ignore the rest
Unfortunately it throws if data is too big. You would have to find different implementation of gzip or maybe put it into webworker to workaround that.

javascript: clean way of converting currencies from an array

Folks!
Currently i have written this below code, which converts one currencies into another , but the problem is i am defining each & every currencies one by one in switch block,
If i have 100 currencies to convert then i have to write 100 switch cases
Is there any i can make this below code dynamic and short?
var currencies = {};
$(document).ready(function(){
yahoo_getdata();
});
function yahoo_getdata() {
var a = new Date();
var b = "http://someAPIurl.com/webservice/v1/symbols/allcurrencies/quote?format=json&random=" + a.getTime() + "&callback=?";
$.getJSON(b, function (e) {
if (e) {
var i, l, r, c;
r = e.list.resources;
for (i = 0, l = r.length; i < l; i += 1) {
c = r[i].resource.fields;
//console.log(c.name, c.price);
switch (c.name) {
case "USD/EUR":
currencies.EUR = c.price;
console.log('USD/EUR = ' + c.price);
break;
case "USD/USD":
currencies.USD = c.price;
console.log('USD/USD = ' + c.price);
break;
case "USD/JPY":
currencies.JPY = c.price;
console.log('USD/JPY = ' + c.price);
break;
case "USD/INR":
currencies.INR = c.price;
console.log('USD/INR = ' + c.price);
break;
}
}
console.log(currencies);
//console.log(e);
//var d = {};
}
});
}
$("#amount1").keyup(function() {
var
usd,
amount1 = $('#amount1').val(),
currency1 = $("#currency1").val(),
currency2 = $("#currency2").val();
// normalize to USD
usd = amount1 / currencies[currency1];
// convert to target currency
$('#amount2').val(usd * currencies[currency2]);
});
Use an object that maps the currency name to the object property name:
var currency_map = {
'USD/EUR': 'EUR',
'USD/USD': 'USD',
'USD/JPY': 'JPY',
...
};
Then:
for (var i = 0, l = r.length; i < l; i++) {
c = r[i].resource.fields;
currencies[currency_map[c.name] || c.name] = c.price;
console.log(c.name + ' = ' + c.price);
}
FIDDLE

JavaScript using a for loop with an array spliting array

Hey guys i need some code that will split an array that holds a string which is an item and amount with the delimiter being the (:). (eg. Gas:30 )
loading the elements from the transArray into the values of hmtl texboxes for the item and amount fields
Please don't be to harsh with the comments this is my first language for a type-language.
Any help is appreciated!
var load = function ()
{
mySetArray(); //Fills the transArray randomly with 1-4 items
var item = '';
var amount = '';
for ( i=1; i<=transArray.length; i++)
{
item = 'item' + i;
amount = 'amount' + i;
transArray.split(":");
}
}
var mySetArray = function ()
{
var myRandom = Math.floor((Math.random() * 100) / 25) + 1; //a number between 1 and 4
transArray = new Array(); //Resets the Array to empty
if (myRandom == 1)
{
transArray[0] = "Food:200";
}
if (myRandom == 2)
{
transArray[0] = "Food:200";
transArray[1] = "Toys:700";
}
if (myRandom == 3)
{
transArray[0] = "Food:200";
transArray[1] = "Toys:700";
transArray[2] = "Mortgage:1800";
}
if (myRandom == 4)
{
transArray[0] = "Food:200";
transArray[1] = "Toys:700";
transArray[2] = "Mortgage:1800";
transArray[3] = "Cable:130";
}
}
window.onload = function ()
{
$("load").onclick = load;
}
To split an array, such as:
transArray[0] = "Food:200";
Just use split:
var newArray = transArray[0].split(':');
// newArray[0] = 'Food', newArray[1] = '200'
change:
for ( i=1; i<=transArray.length; i++) {
item = 'item' + i;
amount = 'amount' + i;
transArray.split(":");
}
to
for ( i=1; i<=transArray.length; i++) {
item = 'item' + i;
amount = 'amount' + i;
var splitted = transArray[i].split(":"); <-- split each item in transArray
console.log(splitted);
}
Here transArray is an array. You should use split on it's values i.e transArray[i].split(":");
So update your code like this :
for ( i=1; i<=transArray.length; i++)
{
item = 'item' + i;
amount = 'amount' + i;
var splittedData = transArray[i].split(":");
// It will give Item in 0th index and amount in 1st field.
}
var arr = new Array();
arr[0] = "Gas:200";
var newArr = arr[0].split(':');
JSFIDDLE DEMO
Call load function where ever you want or as it is (as i have done)
function load()
{
transArray = mySetArray(); //Fills the transArray randomly with 1-4 items
var item = '';
var amount = '';
for ( i=0; i<=transArray.length; i++)
{
ar = transArray[i].split(":");
alert((i+1)+" Item="+ar[0] + " Amount="+ ar[1]); // You ca use it in your own way
}
}
load();
function mySetArray()
{
var myRandom = Math.floor((Math.random() * 100) / 25) + 1; //a number between 1 and 4
transArray = new Array(); //Resets the Array to empty
if (myRandom == 1)
{
transArray.push("Food:200");
}
if (myRandom == 2)
{
transArray.push("Food:200");
transArray.push("Toys:700");
}
if (myRandom == 3)
{
transArray.push("Food:200");
transArray.push("Toys:700");
transArray.push("Mortgage:1800");
}
if (myRandom == 4)
{
transArray.push("Food:200");
transArray.push("Toys:700");
transArray.push("Mortgage:1800");
transArray.push("Cable:130");
}
return transArray;
}

Javascript error after upgrade to Drupal 7

I posted a similar question at the Drupal Forum, but I haven't had much luck.
I'm upgrading a site from D6 to D7. So far it's gone well, but I'm getting a Javascript error that I just can't pin down a solution for.
This is a cut down version of the whole script:
(function($) {
function sign(secret, message) {
var messageBytes = str2binb(message);
var secretBytes = str2binb(secret);
if (secretBytes.length > 16) {
secretBytes = core_sha256(secretBytes, secret.length * chrsz);
}
var ipad = Array(16), opad = Array(16);
for (var i = 0; i < 16; i++) {
ipad[i] = secretBytes[i] ^ 0x36363636;
opad[i] = secretBytes[i] ^ 0x5C5C5C5C;
}
var imsg = ipad.concat(messageBytes);
var ihash = core_sha256(imsg, 512 + message.length * chrsz);
var omsg = opad.concat(ihash);
var ohash = core_sha256(omsg, 512 + 256);
var b64hash = binb2b64(ohash);
var urlhash = encodeURIComponent(b64hash);
return urlhash;
}
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
Date.prototype.toISODate =
new Function("with (this)\nreturn " +
"getFullYear()+'-'+addZero(getMonth()+1)+'-'" +
"+addZero(getDate())+'T'+addZero(getHours())+':'" +
"+addZero(getMinutes())+':'+addZero(getSeconds())+'.000Z'");
function getNowTimeStamp() {
var time = new Date();
var gmtTime = new Date(time.getTime() + (time.getTimezoneOffset() * 60000));
return gmtTime.toISODate() ;
}
}(jQuery));
The part that keeps throwing an error I'm seeing in Firebug is at:
Date.prototype.toISODate =
new Function("with (this)\n return " +
"getFullYear()+'-'+addZero(getMonth()+1)+'-'" +
"+addZero(getDate())+'T'+addZero(getHours())+':'" +
"+addZero(getMinutes())+':'+addZero(getSeconds())+'.000Z'");
Firebug keeps stopping at "addZero is not defined". JS has never been my strong point, and I know some changes have been made in D7. I've already wrapped the entire script in "(function($) { }(jQuery));", but I must be missing something else. The same script works perfectly on the D6 site.
Here is the "fixed" version of the whole code with #Pointy suggestion added. All I left out is the part of the script for making the hash that goes to Amazon, and some of my declared variables.
(function($) {
var typedText;
var strSearch = /asin:/;
var srchASIN;
$(document).ready(function() {
$("#edit-field-game-title-und-0-asin").change(function() {
typedText = $("#edit-field-game-title-und-0-asin").val();
$.ajax({
type: 'POST',
data: {typedText: typedText},
dataType: 'text',
url: '/asin/autocomplete/',
success:function(){
document.getElementById('asin-lookup').style.display='none';
x = typedText.search(strSearch);
y = (x+5);
srchASIN = typedText.substr(y,10)
amazonSearch();
}
});
});
$("#search_asin").click(function() {
$("#edit-field-game-title-und-0-asin").val('');
document.getElementById('name-lookup').style.display='none';
$("#edit-field-game-title-und-0-asin").val('');
$("#edit-title").val('');
$("#edit-field-subtitle-und-0-value").val('');
$("#edit-field-game-edition-und-0-value").val('');
$("#edit-field-release-date-und-0-value-date").val('');
$("#edit-field-asin-und-0-asin").val('');
$("#edit-field-ean-und-0-value").val('');
$("#edit-field-amazon-results-und-0-value").val('');
$("#edit-body").val('');
srchASIN = $("#field-asin-enter").val();
amazonSearch();
});
$("#clear_search").click(function() {
$("#field-asin-enter").val('');
$("#edit-field-game-title-und-0-asin").val('');
$("#edit-title").val('');
$("#edit-field-subtitle-und-0-value").val('');
$("#edit-field-game-edition-und-0-value").val('');
$("#edit-field-release-date-und-0-value-date").val('');
$("#edit-field-release-dt2-und-0-value-date").val('');
$("#edit-field-asin-und-0-asin").val('');
$("#edit-field-ean-und-0-value").val('');
$("#edit-field-amazon-results-und-0-value").val('');
$("#field-amazon-platform").val('');
$("#field-amazon-esrb").val('');
$("#edit-body-und-0-value").val('');
document.getElementById('asin-lookup').style.display='';
document.getElementById('name-lookup').style.display='';
});
function amazonSearch(){
var ASIN = srchASIN;
var azScr = cel("script");
azScr.setAttribute("type", "text/javascript");
var requestUrl = invokeRequest(ASIN);
azScr.setAttribute("src", requestUrl);
document.getElementsByTagName("head").item(0).appendChild(azScr);
}
});
var amzJSONCallback = function(tmpData){
if(tmpData.Item){
var tmpItem = tmpData.Item;
}
$("#edit-title").val(tmpItem.title);
$("#edit-field-game-edition-und-0-value").val(tmpItem.edition);
$("#edit-field-release-date-und-0-value-date").val(tmpItem.relesdate);
$("#edit-field-release-dt2-und-0-value-date").val(tmpItem.relesdate);
$("#edit-field-asin-und-0-asin").val(tmpItem.asin);
$("#edit-field-ean-und-0-value").val(tmpItem.ean);
$("#field-amazon-platform").val(tmpItem.platform);
$("#field-amazon-publisher").val(tmpItem.publisher);
$("#field-amazon-esrb").val(tmpItem.esrb);
};
function ctn(x){ return document.createTextNode(x); }
function cel(x){ return document.createElement(x); }
function addEvent(obj,type,fn){
if (obj.addEventListener){obj.addEventListener(type,fn,false);}
else if (obj.attachEvent){obj["e"+type+fn]=fn; obj.attachEvent("on"+type,function(){obj["e"+type+fn]();});}
}
var styleXSL = "http://www.tlthost.net/sites/vglAmazonAsin.xsl";
function invokeRequest(ASIN) {
cleanASIN = ASIN.replace(/[-' ']/g,'');
var unsignedUrl = "http://xml-us.amznxslt.com/onca/xml?Service=AWSECommerceService&AssociateTag=theliterarytimes&IdType=ASIN&ItemId="+cleanASIN+"&Operation=ItemLookup&ResponseGroup=Medium,ItemAttributes,OfferFull&Style="+styleXSL+"&ContentType=text/javascript&CallBack=amzJSONCallback";
var lines = unsignedUrl.split("\n");
unsignedUrl = "";
for (var i in lines) { unsignedUrl += lines[i]; }
// find host and query portions
var urlregex = new RegExp("^http:\\/\\/(.*)\\/onca\\/xml\\?(.*)$");
var matches = urlregex.exec(unsignedUrl);
var host = matches[1].toLowerCase();
var query = matches[2];
// split the query into its constituent parts
var pairs = query.split("&");
// remove signature if already there
// remove access key id if already present
// and replace with the one user provided above
// add timestamp if not already present
pairs = cleanupRequest(pairs);
// encode the name and value in each pair
pairs = encodeNameValuePairs(pairs);
// sort them and put them back together to get the canonical query string
pairs.sort();
var canonicalQuery = pairs.join("&");
var stringToSign = "GET\n" + host + "\n/onca/xml\n" + canonicalQuery;
// calculate the signature
//var secret = getSecretAccessKey();
var signature = sign(secret, stringToSign);
// assemble the signed url
var signedUrl = "http://" + host + "/onca/xml?" + canonicalQuery + "&Signature=" + signature;
//document.write ("<html><body><pre>REQUEST: "+signedUrl+"</pre></body></html>");
return signedUrl;
}
function encodeNameValuePairs(pairs) {
for (var i = 0; i < pairs.length; i++) {
var name = "";
var value = "";
var pair = pairs[i];
var index = pair.indexOf("=");
// take care of special cases like "&foo&", "&foo=&" and "&=foo&"
if (index == -1) {
name = pair;
} else if (index == 0) {
value = pair;
} else {
name = pair.substring(0, index);
if (index < pair.length - 1) {
value = pair.substring(index + 1);
}
}
// decode and encode to make sure we undo any incorrect encoding
name = encodeURIComponent(decodeURIComponent(name));
value = value.replace(/\+/g, "%20");
value = encodeURIComponent(decodeURIComponent(value));
pairs[i] = name + "=" + value;
}
return pairs;
}
function cleanupRequest(pairs) {
var haveTimestamp = false;
var haveAwsId = false;
var nPairs = pairs.length;
var i = 0;
while (i < nPairs) {
var p = pairs[i];
if (p.search(/^Timestamp=/) != -1) {
haveTimestamp = true;
} else if (p.search(/^(AWSAccessKeyId|SubscriptionId)=/) != -1) {
pairs.splice(i, 1, "AWSAccessKeyId=" + accessKeyId);
haveAwsId = true;
} else if (p.search(/^Signature=/) != -1) {
pairs.splice(i, 1);
i--;
nPairs--;
}
i++;
}
if (!haveTimestamp) {
pairs.push("Timestamp=" + getNowTimeStamp());
}
if (!haveAwsId) {
pairs.push("AWSAccessKeyId=" + accessKeyId);
}
return pairs;
}
function sign(secret, message) {
var messageBytes = str2binb(message);
var secretBytes = str2binb(secret);
if (secretBytes.length > 16) {
secretBytes = core_sha256(secretBytes, secret.length * chrsz);
}
var ipad = Array(16), opad = Array(16);
for (var i = 0; i < 16; i++) {
ipad[i] = secretBytes[i] ^ 0x36363636;
opad[i] = secretBytes[i] ^ 0x5C5C5C5C;
}
var imsg = ipad.concat(messageBytes);
var ihash = core_sha256(imsg, 512 + message.length * chrsz);
var omsg = opad.concat(ihash);
var ohash = core_sha256(omsg, 512 + 256);
var b64hash = binb2b64(ohash);
var urlhash = encodeURIComponent(b64hash);
return urlhash;
}
Date.prototype.toISODate = function() {
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
var d = this;
return d.getFullYear() + '-' +
addZero(d.getMonth() + 1) + '-' +
addZero(d.getDate()) + 'T' +
addZero(d.getHours()) + ':' +
addZero(d.getMinutes()) + ':' +
addZero(d.getSeconds()) + '.000Z';
};
function getNowTimeStamp() {
var time = new Date();
var gmtTime = new Date(time.getTime() + (time.getTimezoneOffset() * 60000));
return gmtTime.toISODate() ;
}
}(jQuery));
Here's a better version of your code:
Date.prototype.toISODate = function() {
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
var d = this;
return d.getFullYear() + '-' +
addZero(d.getMonth() + 1) + '-' +
addZero(d.getDate()) + 'T' +
addZero(d.getHours()) + ':' +
addZero(d.getMinutes()) + ':' +
addZero(d.getSeconds()) + '.000Z';
};
That moves "addDate" inside the extension function, and it avoids the horrid with statement.

Categories