javascript: clean way of converting currencies from an array - javascript

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

Related

Brainlabs adwords script remove firstpagemaxbid restriction

Can some body help me modify this script.
The purpose of the script is to change bids for the keywords based on average position. One of the assumptions that the script has is that it sets a firstpagebid for the keyword but it won't allow for the bid to go below the firstpagebid even if the position is too high.
Is there a way to remove this restriction? so basically if the new cpc calculated is lower than the first page bid then it allows for the new cpc to be lower than the firstpage bid.
/**
*
* Average Position Bidding Tool
*
* This script changes keyword bids so that they target specified positions,
* based on recent performance.
*
* Version: 1.5
* Updated 2015-09-28 to correct for report column name changes
* Updated 2016-02-05 to correct label reading, add extra checks and
* be able to adjust maximum bid increases and decreases separately
* Updated 2016-08-30 to correct label reading from reports
* Updated 2016-09-14 to update keywords in batches
* Updated 2016-10-26 to avoid DriveApp bug
* Google AdWords Script maintained on brainlabsdigital.com
*
**/
// Options
var maxBid = 14.50;
// Bids will not be increased past this maximum.
var minBid = 3.0;
// Bids will not be decreased below this minimum.
var firstPageMaxBid = 10.00;
// The script avoids reducing a keyword's bid below its first page bid estimate. If you think
// Google's first page bid estimates are too high then use this to overrule them.
var dataFile = "AveragePositionData.txt";
// This name is used to create a file in your Google Drive to store today's performance so far,
// for reference the next time the script is run.
var useFirstPageBidsOnKeywordsWithNoImpressions = true;
// If this is true, then if a keyword has had no impressions since the last time the script was run
// its bid will be increased to the first page bid estimate (or the firsPageMaxBid if that is smaller).
// If this is false, keywords with no recent impressions will be left alone.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Advanced Options
var bidIncreaseProportion = 0.20;
var bidDecreaseProportion = 0.25;
var targetPositionTolerance = 0.3;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function main() {
var fieldJoin = ",";
var lineJoin = "$";
var idJoin = "#";
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
/*var files = DriveApp.getFilesByName(dataFile);
if (!files.hasNext()) {
var file = DriveApp.createFile(dataFile,"\n");
Logger.log("File '" + dataFile + "' has been created.");
} else {
var file = files.next();
if (files.hasNext()) {
Logger.log("Error - more than one file named '" + dataFile + "'");
return;
}
Logger.log("File '" + dataFile + "' has been read.");
}*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Get the current date/time
var currentTime = new Date(Utilities.formatDate(new Date(), AdWordsApp.currentAccount().getTimeZone(), "MMM dd,yyyy HH:mm:ss"));
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var hourOfDay = currentTime.getHours();
var dayOfWeek = days[currentTime.getDay()]; //Added on 9/21/2015
// Prevent adjustments if not in between 8am and 11pm and Diffrent running time by date - Added on 9/21/2015 (important allows to set time based on day)
switch (dayOfWeek) {
case 'Monday':
case 'Tuesday':
case 'Wednesday':
case 'Thursday':
case 'Friday':
if (hourOfDay < 8 || hourOfDay >= 21) {
Logger.log("Not the Right Time");
return;
}
break;
case 'Saturday':
case 'Sunday':
if (hourOfDay < 8 || hourOfDay >= 18) {
Logger.log("Not the Right Time");
return;
}
break;
}
Logger.log("Right Time");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var labelIds = [];
var labelIterator = AdWordsApp.labels()
.withCondition("KeywordsCount > 0")
.withCondition("LabelName CONTAINS_IGNORE_CASE 'Position '")
.get();
while (labelIterator.hasNext()) {
var label = labelIterator.next();
if (label.getName().substr(0,"position ".length).toLowerCase() == "position ") {
labelIds.push(label.getId());
}
}
if (labelIds.length == 0) {
Logger.log("No position labels found.");
return;
}
Logger.log(labelIds.length + " position labels have been found.");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var keywordData = {
//UniqueId1: {LastHour: {Impressions: , AveragePosition: }, ThisHour: {Impressions: , AveragePosition: },
//CpcBid: , FirstPageCpc: , MaxBid, MinBid, FirstPageMaxBid, PositionTarget: , CurrentAveragePosition:,
//Criteria: }
}
var ids = [];
var uniqueIds = [];
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var report = AdWordsApp.report(
'SELECT Id, Criteria, AdGroupId, AdGroupName, CampaignName, Impressions, AveragePosition, CpcBid, FirstPageCpc, Labels, BiddingStrategyType ' +
'FROM KEYWORDS_PERFORMANCE_REPORT ' +
'WHERE Status = ENABLED AND AdGroupStatus = ENABLED AND CampaignStatus = ENABLED ' +
'AND LabelIds CONTAINS_ANY [' + labelIds.join(",") + '] ' +
'AND AdNetworkType2 = SEARCH ' +
'AND Device NOT_IN ["HIGH_END_MOBILE"] ' +
'DURING TODAY'
);
var rows = report.rows();
while(rows.hasNext()){
var row = rows.next();
if (row["BiddingStrategyType"] != "cpc") {
if (row["BiddingStrategyType"] == "Enhanced CPC"
|| row["BiddingStrategyType"] == "Target search page location"
|| row["BiddingStrategyType"] == "Target Outranking Share"
|| row["BiddingStrategyType"] == "None"
|| row["BiddingStrategyType"] == "unknown") {
Logger.log("Warning: keyword " + row["Criteria"] + "' in campaign '" + row["CampaignName"] +
"' uses '" + row["BiddingStrategyType"] + "' rather than manual CPC. This may overrule keyword bids and interfere with the script working.");
} else {
Logger.log("Warning: keyword " + row["Criteria"] + "' in campaign '" + row["CampaignName"] +
"' uses the bidding strategy '" + row["BiddingStrategyType"] + "' rather than manual CPC. This keyword will be skipped.");
continue;
}
}
var positionTarget = "";
if (row["Labels"].trim() == "--") {
continue;
}
var labels = JSON.parse(row["Labels"].toLowerCase()); // Labels are returned as a JSON formatted string
for (var i=0; i<labels.length; i++) {
if (labels[i].substr(0,"position ".length) == "position ") {
var positionTarget = parseFloat(labels[i].substr("position ".length-1).replace(/,/g,"."),10);
break;
}
}
if (positionTarget == "") {
continue;
}
if (integrityCheck(positionTarget) == -1) {
Logger.log("Invalid position target '" + positionTarget + "' for keyword '" + row["Criteria"] + "' in campaign '" + row["CampaignName"] + "'");
continue;
}
ids.push(parseFloat(row['Id'],10));
var uniqueId = row['AdGroupId'] + idJoin + row['Id'];
uniqueIds.push(uniqueId);
keywordData[uniqueId] = {};
keywordData[uniqueId]['Criteria'] = row['Criteria'];
keywordData[uniqueId]['ThisHour'] = {};
keywordData[uniqueId]['ThisHour']['Impressions'] = parseFloat(row['Impressions'].replace(/,/g,""),10);
keywordData[uniqueId]['ThisHour']['AveragePosition'] = parseFloat(row['AveragePosition'].replace(/,/g,""),10);
keywordData[uniqueId]['CpcBid'] = parseFloat(row['CpcBid'].replace(/,/g,""),10);
keywordData[uniqueId]['FirstPageCpc'] = parseFloat(row['FirstPageCpc'].replace(/,/g,""),10);
setPositionTargets(uniqueId, positionTarget);
}
Logger.log(uniqueIds.length + " labelled keywords found");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
setBidChange();
setMinMaxBids();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
/* var currentHour = parseInt(Utilities.formatDate(new Date(), AdWordsApp.currentAccount().getTimeZone(), "HH"), 10);
if (currentHour != 0) {
var data = file.getBlob().getDataAsString();
var data = data.split(lineJoin);
for(var i = 0; i < data.length; i++){
data[i] = data[i].split(fieldJoin);
var uniqueId = data[i][0];
if(keywordData.hasOwnProperty(uniqueId)){
keywordData[uniqueId]['LastHour'] = {};
keywordData[uniqueId]['LastHour']['Impressions'] = parseFloat(data[i][1],10);
keywordData[uniqueId]['LastHour']['AveragePosition'] = parseFloat(data[i][2],10);
}
}
}*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
findCurrentAveragePosition();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Batch the keyword IDs, as the iterator can't take them all at once
var idBatches = [];
var batchSize = 5000;
for (var i=0; i<uniqueIds.length; i += batchSize) {
idBatches.push(uniqueIds.slice(i,i+batchSize));
}
Logger.log("Updating keywords");
// Update each batch
for (var i=0; i<idBatches.length; i++) {
try {
updateKeywords(idBatches[i]);
} catch (e) {
Logger.log("Error updating keywords: " + e);
Logger.log("Retrying after one minute.");
Utilities.sleep(60000);
updateKeywords(idBatches[i]);
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Logger.log("Writing file.");
// var content = resultsString();
// file.setContent(content);
Logger.log("Finished.");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Functions
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function integrityCheck(target){
var n = parseFloat(target, 10);
if(!isNaN(n) && n >= 1){
return n;
}
else{
return -1;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setPositionTargets(uniqueId, target){
if(target !== -1){
keywordData[uniqueId]['HigherPositionTarget'] = Math.max(target-targetPositionTolerance, 1);
keywordData[uniqueId]['LowerPositionTarget'] = target+targetPositionTolerance;
}
else{
keywordData[uniqueId]['HigherPositionTarget'] = -1;
keywordData[uniqueId]['LowerPositionTarget'] = -1;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function bidChange(uniqueId){
var newBid = -1;
if(keywordData[uniqueId]['HigherPositionTarget'] === -1){
return newBid;
}
var cpcBid = keywordData[uniqueId]['CpcBid'];
var minBid = keywordData[uniqueId]['MinBid'];
var maxBid = keywordData[uniqueId]['MaxBid'];
if (isNaN(keywordData[uniqueId]['FirstPageCpc'])) {
Logger.log("Warning: first page CPC estimate is not a number for keyword '" + keywordData[uniqueId]['Criteria'] + "'. This keyword will be skipped");
return -1;
}
var firstPageBid = Math.min(keywordData[uniqueId]['FirstPageCpc'], keywordData[uniqueId]['FirstPageMaxBid'], maxBid);
var currentPosition = keywordData[uniqueId]['CurrentAveragePosition'];
var higherPositionTarget = keywordData[uniqueId]['HigherPositionTarget'];
var lowerPositionTarget = keywordData[uniqueId]['LowerPositionTarget'];
var bidIncrease = keywordData[uniqueId]['BidIncrease'];
var bidDecrease = keywordData[uniqueId]['BidDecrease'];
if((currentPosition > lowerPositionTarget) && (currentPosition !== 0)){
var linearBidModel = Math.min(2*bidIncrease,(2*bidIncrease/lowerPositionTarget)*(currentPosition-lowerPositionTarget));
var newBid = Math.min((cpcBid + linearBidModel), maxBid);
}
if((currentPosition < higherPositionTarget) && (currentPosition !== 0)) {
var linearBidModel = Math.min(2*bidDecrease,((-4)*bidDecrease/higherPositionTarget)*(currentPosition-higherPositionTarget));
var newBid = Math.max((cpcBid-linearBidModel),minBid);
if (cpcBid > firstPageBid) {
var newBid = Math.max(firstPageBid,newBid);
}
}
if((currentPosition === 0) && useFirstPageBidsOnKeywordsWithNoImpressions && (cpcBid < firstPageBid)){
var newBid = firstPageBid;
}
if (isNaN(newBid)) {
Logger.log("Warning: new bid is not a number for keyword '" + keywordData[uniqueId]['Criteria'] + "'. This keyword will be skipped");
return -1;
}
return newBid;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function findCurrentAveragePosition(){
for(var x in keywordData){
if(keywordData[x].hasOwnProperty('LastHour')){
keywordData[x]['CurrentAveragePosition'] = calculateAveragePosition(keywordData[x]);
} else {
keywordData[x]['CurrentAveragePosition'] = keywordData[x]['ThisHour']['AveragePosition'];
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function calculateAveragePosition(keywordDataElement){
var lastHourImpressions = keywordDataElement['LastHour']['Impressions'];
var lastHourAveragePosition = keywordDataElement['LastHour']['AveragePosition'];
var thisHourImpressions = keywordDataElement['ThisHour']['Impressions'];
var thisHourAveragePosition = keywordDataElement['ThisHour']['AveragePosition'];
if(thisHourImpressions == lastHourImpressions){
return 0;
}
else{
var currentPosition = (thisHourImpressions*thisHourAveragePosition-lastHourImpressions*lastHourAveragePosition)/(thisHourImpressions-lastHourImpressions);
if (currentPosition < 1) {
return 0;
} else {
return currentPosition;
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function keywordUniqueId(keyword){
var id = keyword.getId();
var idsIndex = ids.indexOf(id);
if(idsIndex === ids.lastIndexOf(id)){
return uniqueIds[idsIndex];
}
else{
var adGroupId = keyword.getAdGroup().getId();
return adGroupId + idJoin + id;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setMinMaxBids(){
for(var x in keywordData){
keywordData[x]['MinBid'] = minBid;
keywordData[x]['MaxBid'] = maxBid;
keywordData[x]['FirstPageMaxBid'] = firstPageMaxBid;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setBidChange(){
for(var x in keywordData){
keywordData[x]['BidIncrease'] = keywordData[x]['CpcBid'] * bidIncreaseProportion/2;
keywordData[x]['BidDecrease'] = keywordData[x]['CpcBid'] * bidDecreaseProportion/2;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function updateKeywords(idBatch) {
var keywordIterator = AdWordsApp.keywords()
.withIds(idBatch.map(function(str){return str.split(idJoin);}))
.get();
while(keywordIterator.hasNext()){
var keyword = keywordIterator.next();
var uniqueId = keywordUniqueId(keyword);
var newBid = bidChange(uniqueId);
if(newBid !== -1){
keyword.setMaxCpc(newBid);
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
/*function resultsString(){
var results = [];
for(var uniqueId in keywordData){
var resultsRow = [uniqueId, keywordData[uniqueId]['ThisHour']['Impressions'], keywordData[uniqueId]['ThisHour']['AveragePosition']];
results.push(resultsRow.join(fieldJoin));
}
return results.join(lineJoin);
}*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
}
As I understand, the script increases the cpcBid when the current average position is too high, and decreases it when the position is too low.
But when the bid is decreased and the previous bid is more than firstPageBid, the new bid will not decrease below firstPageBid.
Remove
if (cpcBid > firstPageBid) {
var newBid = Math.max(firstPageBid,newBid);
}
to allow your new bid to go lower than firstPageBid.

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.

Making array from user input (Seperated by linebreaks) with Javascript

I am trying to take user input in form of a lot of strings. I want to store them in an array, and the input should be seperated by line breaks.
It should be very much like this: https://www.random.org/lists/
I can not grasp where to being - can someone help? I am using JavaScript but any solutions using JS or jQuery would be great!
I have posted my JS. I want the var people from user input, instead of having to populate the array myself.
Thanks,
$(document).ready(function() {
$(".btn").on('click', function() {
var people = ["Markus Eriksson", "Leticia Hoshino", "Yemi Afolabi", "Eskil Fogelström", "Josefina Liedberg", "David Bjørn Bograd", "Tilda Dahlgren", "Damien Vignol", "Sofie Cousu", "Carolina Lindelöw", "Bilal Khan", "Louise Brandrup-Wognsen", "Emilia Lehto", "Albin Hagström",
"Victor Borg", "Anna Stella Lo-Ré", "Loucmane", "Angelica Ruth", "Victoria VL", "Johan Hellström", "Micke Skoglund", "Anna Unger", "Isaac Sennerholt", "Cyndie Léa Vintilescu", "Mahle Rakela Robin", "Louise Ek", "Ibrahim Bajwa", "Abodi Ismail",
"Alex Ashman", "Elin Grass Casalini", "Amanda Schultz", "Abenezer Abebe", "Julia Hoff", "Enny Hellsén", "Michel George", "Abdullahi Hussein", "Teodor Meurling", "Andrea Sami Mogren", "Thea Arpine Gasparyan", "Jakob Eberson"
];
var groupSize = $("input[name=checkListItem]").val();
var groups = [];
$(".group").remove();
// Randomizing function
Array.prototype.shuffle = function() {
var input = this;
for (var i = input.length - 1; i >= 0; i--) {
var randomIndex = Math.floor(Math.random() * (i + 1));
var itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
return input;
};
people.shuffle();
// Split people into chunks and push new arrays into var groups
while (people.length > 0) {
chunks = people.splice(0, groupSize);
var chunksSpace = chunks.join(', ');
groups.push(chunksSpace);
}
// Append the groups into the DOM
$(document).ready(function() {
for (var i = 0; i < groups.length; i++) {
$('.all-groups').append("<div class='group'><p><span class='groupheader'>Group " + (i + 1) + "</span></br> " + groups[i] + "</p></div>");
}
});
});
});
Pure Javascript
document.getElementById("element_id").value.split("\n");
OR JQuery $("#element_id").val().split("\n");
For your example give your input id='people' and should work, also avoid extra line breaks by .replace(/\n+/g,"\n").
$(document).ready(function() {
// Randomizing function
Array.prototype.shuffle = function() {
var input = this;
for (var i = input.length - 1; i >= 0; i--) {
var randomIndex = Math.floor(Math.random() * (i + 1));
var itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
return input;
};
$(".btn").on('click', function() {
var people = $("#people").val().replace(/\n+/g,"\n").split("\n");
var groupSize = $("input[name=checkListItem]").val();
var groups = [];
$(".group").remove();
people.shuffle();
// Split people into chunks and push new arrays into var groups
while (people.length > 0) {
chunks = people.splice(0, groupSize);
var chunksSpace = chunks.join(', ');
groups.push(chunksSpace);
}
// Append the groups into the DOM
$(document).ready(function() {
for (var i = 0; i < groups.length; i++) {
$('.all-groups').append("<div class='group'><p><span class='groupheader'>Group " + (i + 1) + "</span></br> " + groups[i] + "</p></div>");
}
});
});
});
var text = $('#total-number').text();
var eachLine = text.split('\n');
alert('Lines found: ' + eachLine.length);
for(var i = 0, l = eachLine.length; i < l; i++) {
alert('Line ' + (i+1) + ': ' + eachLine[i]);
}
Use split to split a multi line string into parts:
var textarea = document.querySelector("textarea");
textarea.addEventListener("change", function(e) {
console.log(textarea.value.split((/[\n\r]/g)));
});
<textarea></textarea>
Regex links:
\r
\n

Stuck on Converting a JS function to Perl

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;
}

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