How to switch two letters in a string - javascript

var dkey = ""
function changekey(decryptionkey){
dkey = decryptionkey
var Ranint = Math.floor(Math.random() * 25) + 1
var Ranint2 = Math.floor(Math.random() * 25) + 1
if(Ranint===Ranint2){
Ranint2+=1
if(Ranint2>25){
Ranint2-=3
}
}
key = key.replace(key.charAt(Ranint),key.charAt(Ranint2))
}
changekey(key)
alert(key)
Say Ranint = 1 and Ranint2 = 2 then key would be
"BBCDEFGHIJKLMNOPQRSTUVWXYZ"
My question is how I would change the code for the key to result in
"BACDEFGHIJKLMNOPQRSTUVWXYZ"

String.prototype.setCharAt = function(index,chr) {
if(index > this.length-1) return str;
return this.substr(0,index) + chr + this.substr(index+1);
}
var dkey = "";
function changekey(decryptionkey){
dkey = decryptionkey;
var Ranint = Math.floor(Math.random() * 25) + 1;
var Ranint2 = Math.floor(Math.random() * 25) + 1;
if(Ranint===Ranint2){
Ranint2+=1;
if(Ranint2>25){
Ranint2-=3;
}
}
var firstChar = dkey.charAt(Ranint);
var secondChar = dkey.charAt(Ranint2);
dkey = dkey.setCharAt(Ranint2, firstChar);
dkey = dkey.setCharAt(Ranint, secondChar);
return dkey;
}
alert(changekey("ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
The DEMO

This is just an alternative could be worth to consider, to find the right one:
var myStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
function switchChar(str)
{
var randomA = getExclusiveRandom(str);
var randomB = getExclusiveRandom(str, randomA);
var replaceA = str[randomA];
var replaceB = str[randomB];
str = str.split("");
str[randomA] = "["+replaceB+"]";
str[randomB] = "["+replaceA+"]";
return str.join("");
}
function getExclusiveRandom(str, exclude)
{
var res = Math.floor(Math.random() * str.length) + 1;
if(!exclude)
{
return res;
}
else
{
if(res === exclude)
{
res = getExclusiveRandom(str, exclude);
}
return res;
}
}
console.info(switchChar(myStr));

Related

Increment digit part of string in JavaScript

I have a string that contains digit at the end. I want to increase the digit part by 1 when some actions happened.
e.g.
var myString = 'AA11111'
increaseStringValue(myString)
# myString new value => 'AA11112'
also how can I increase chars when string value reached to 'AA99999' so new value of string will be 'AB11111'?
You can split char and digit parts so you can handle them separately.
like:
function increaseStringValue(str){
let charPart = str.substring(0,2);
let digitPart = str.substring(2);
digitPart = +digitPart+1
if(digitPart >= 99999){
digitPart = 11111;
if(charPart[1] == 'Z'){
if(charPart[0] == 'Z'){
throw 'Overflow happened'
}
charPart = String.fromCharCode(charPart.charCodeAt(0)+1) + 'A'
}else{
charPart = charPart[0] + String.fromCharCode(charPart.charCodeAt(1)+1)
}
}
return charPart + digitPart;
}
increaseStringValue('AA11111'); // 'AA11112'
increaseStringValue('AA99999'); // 'AB11111'
increaseStringValue('AZ99999'); // 'BA11111'
increaseStringValue('ZZ99999'); // Exception: Overflow happened
This links will be helpful for you:
ASCII CODES
what is a method that can be used to increment letters?
Edit:
Following function will be suite for unknown length string with dynamic position of char and digit.
function increaseStringValue(str) {
let charOverFlowed = true;
let result = ""
for (let i = str.length - 1; i >= 0; i--) {
let currentChar = str[i];
if ('123456789'.indexOf(currentChar) !== -1) {
if (charOverFlowed) {
currentChar = +currentChar + 1
charOverFlowed = false;
}
if (currentChar > 9) {
currentChar = 1;
charOverFlowed = true;
}
} else if (charOverFlowed) {
currentChar = String.fromCharCode(currentChar.charCodeAt(0) + 1)
charOverFlowed = false;
if (currentChar > 'Z') {
if(i == 0){
throw 'Overflow Happened'
}
currentChar = 'A'
charOverFlowed = true
}
}
result = currentChar + result;
}
return result;
}
increaseStringValue('AAAACA')
// "AAAACB"
increaseStringValue('AAAACA1111')
// "AAAACA1112"
increaseStringValue('A1')
// "A2"
increaseStringValue('Z')
// Uncaught Overflow Happened
increaseStringValue('A1999')
// "A2111"
function increaseStringValue(myString){
return myString.replace(/\d+/ig, function(a){ return a*1+1;});
}
console.log(increaseStringValue("asg61"));
And for next question:
function increaseStringValue(myString){
return myString.replace(/(A)(\d+)/ig, function(a, b, c){
var r = c*1+1; return r==99999+1?"B11111":"A"+r;
});
}
console.log(increaseStringValue("AA99999"));
And Whole way:
function increaseStringValue(myString){
return myString.replace(/([a-e])(\d+)/ig, function(a, b, c){
var r = c*1+1; return r==99999+1?String.fromCharCode(a.charCodeAt(0)+1)+"11111":b+r;
});
}
console.log(increaseStringValue("AB99999"));
Please find the snippet useful. If this is what you are expecting.
let stringNum = 'AA11111';//initialise string
let clickTriggered = ()=>{
let startString = "AA";
let newNum = ()=>{
let numberPart = stringNum.split("AA")[1];
let lastChar = stringNum[stringNum.length-1];
return Number(numberPart) != NaN || Number(numberPart) <= 99999 ? Number(numberPart)+1 : 11111;
};
stringNum = `${startString}${newNum()}`
console.log(stringNum)
}
<h1 onclick="clickTriggered()">click here</h1>
You can use String#replace and provide your increment logic in the function callback of the string#replace.
const increaseStringValue = (str) => str.replace(/\d+$/, n => n === '99999' ? 11111 : +n + 1);
console.log(increaseStringValue('AA99999'));
console.log(increaseStringValue('AA11315'));
console.log(increaseStringValue('AA11111'));
I solve this with this solution
let app = new Vue({
el: '#app',
data: {
text: "AA995"
},
methods: {
addOneString: function(str) {
var alphabet = 'abcdefghijklmnopqrstuvwxyz',
length = alphabet.length,
result = str,
i = str.length,
value = str;
while(i >= 0) {
var last = str.charAt(--i),
next = '',
carry = false;
if (isNaN(last)) {
index = alphabet.indexOf(last.toLowerCase());
if (index === -1) {
next = last;
carry = true;
}
else {
var isUpperCase = last === last.toUpperCase();
next = alphabet.charAt((index + 1) % length);
if (isUpperCase) {
next = next.toUpperCase();
}
carry = index + 1 >= length;
if (carry && i === 0) {
var added = isUpperCase ? 'A' : 'a';
result = added + next + result.slice(1);
break;
}
}
}
else {
next = +last + 1;
if(next > 9) {
next = 0;
carry = true;
}
if (carry && i === 0) {
result = '1' + next + result.slice(1);
break;
}
}
result = result.slice(0, i) + next + result.slice(i + 1);
if (!carry) {
break;
}
}
console.log("result",result);
if (value !== result ) this.text = result;
}
}
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div class="container" id="app">
<button #click="addOneString(text)">Add one</button>
</br>
<p> {{text}} </p>
</div>

No results display when running JavaScript

I am stumped. I am not receiving any errors or undefined errors when running this code just a blank return and then a new command line. I've run it about 100 times in the command prompt and still nothing. I figured after 100 times it should display the "Congratulations message". Can anyone take a look and see what I am missing? Thank you in advance.
//Player Class
function Player(name, weapons) {
this.playerName = name;
this.playerHealth = 10;
this.playerStrength = 2;
this.playerWeapons = weapons;
}
Player.prototype.applyDamage = function(damage) {
this.playerHealth = this.playerHealth - damage;
console.log(this.playerName + " " + "has sustained " + " " + this.playerHealth + " " + "amount of damage.");
}
Player.prototype.isAlive = function() {
if(this.playerHealth > 0)
return true;
else
return false;
}
Player.prototype.attacksWith = function() {
var random = Math.floor(Math.random() * 8);
return (this.weapon[random]);
}
//Minion Class
function Minion(minion, health, strength) {
this.minionName = 'Minion';
this.minionHealth = 5;
this.minionStrength = 2;
}
Minion.prototype.applyDamage = function(damage) {
this.minionHealth = this.minionHealth - damage;
console.log(this.minionName + " " + "has sustained " + " " + this.minionHealth + " " + "amount of damage.");
}
Minion.prototype.isAlive = function() {
if(this.minionHealth > 0)
return true;
else
return false;
}
Minion.prototype.attack = function(playerName) {
playerName.applyDamage(this.minionHealth);
}
//Weapons Class
function Weapons(weapon) {
this.weaponName = weapon;
this.weapondamage = Math.floor(Math.random() * 5) + 1;
}
var weaponsCache = [];
for (var i = 0; i < 8; i++) {
var axe = new Weapons("skullCracker");
var hxfx = new Weapons("Hexaflexagon");
var blade = new Weapons("Balmung");
var mario = new Weapons("cappy");
var fire = new Weapons("Fire Breath");
var staff = new Weapons("Magic Staff");
var hrp = new Weapons("Harpe");
var CobaltWep = new Weapons("Cobalt Rifle");
var w = new Weapons([i]);
weaponsCache[i] = w;
}
var player = [];
var i = 0;
while (i < 8) {
var m = new Player();
player[i] = m;
i++;
}
//Game Class
function Game(players, minions) {
this.players = [];
this.minions = [];
}
function attack(player, minion) {
while (playerName.isAlive() && minionName.isAlive()) {
actualDamage = player.strength * this.damage();
minion.applyDamage(actualDamage);
if (minion.isAlive())
minion.attack(player);
else
break;
}
}
function createMinions() {
var i = 0;
while (i > 20) {
var m = new Minion();
minion[i] = m;
i++;
}
}
function createPlayers() {
var player = []; {
var ph = new Player("Prophetic Hamster", weaponsCache);
var mm = new Player("Mighty Mathematician", weaponsCache);
var sieg = new Player ("Siegfried", weaponsCache);
var bd = new Player ("Blue Dragon", weaponsCache);
var ip = new Player("Iron Professor", weaponsCache)
}
Game.prototype.play = function() {
console.log("Simulating Battle...");
createMinion();
createPlayer();
var i = 0,
count = 0;
while (i < 20) {
if (minions[i].isAlive())
count++;
}
if (count == 20) {
i = 0;
var flag = 0;
while (i < 8) {
if (players[i].isAlive())
flag++;
}
while (count == 20 && flag > 0) {
var randomPlayer, randomMinion;
randomPlayer = Math.floor(Math.random() * 8);
randomMinion = math.floor(Math.random() * 20);
weapon = player.attackWith();
attack(minions);
attack(players);
}
count = 0;
i = 0;
while (i > 20) {
if (minions[i].isAlive())
count++;
}
flag = 0;
i = 0;
while (i < 8) {
if (players[i].isAlive())
flag++;
}
if (flag > count)
console.log("Congratulations!! You have defeated Scarlet Byte");
}
}
}

Javascript network with labels and weighted edges

I have been searching for quite a while now and I'm not able to find a simple JS library to make a network in which:
The nodes have labels
The edge thickness is proportional to the weight
Able to spread the nodes so that it doesn't get messy.
I found a script on bl.ocks.org which fits my needs, but when I use a lot of nodes it's getting quite messy:
I use this as input:
target,source,weight
woooooow,notgood,70.0
woooooow,gainzz,32.004950495049506
woooooow,test,33.86138613861386
woooooow,peanutss,20.866336633663366
nicecode,woooooow,22.103960396039604
woooooow,oreo,20.742574257425744
bread,woooooow,37.945544554455445
jam,nutella,20.123762376237625
bread,nutsarelol,20.866336633663366
etc
Question
Any ideas which code/library I can use to create a graph like the graph above but with more spreading of the nodes?
JS code
/*
Author: Corneliu S. (github.com/upphiminn)
This is a javascript implementation of the Louvain
community detection algorithm (http://arxiv.org/abs/0803.0476)
Based on https://bitbucket.org/taynaud/python-louvain/overview
*/
(function(){
jLouvain = function(){
//Constants
var __PASS_MAX = -1
var __MIN = 0.0000001
//Local vars
var original_graph_nodes;
var original_graph_edges;
var original_graph = {};
var partition_init;
//Helpers
function make_set(array){
var set = {};
array.forEach(function(d,i){
set[d] = true;
});
return Object.keys(set);
};
function obj_values(obj){
var vals = [];
for( var key in obj ) {
if ( obj.hasOwnProperty(key) ) {
vals.push(obj[key]);
}
}
return vals;
};
function get_degree_for_node(graph, node){
var neighbours = graph._assoc_mat[node] ? Object.keys(graph._assoc_mat[node]) : [];
var weight = 0;
neighbours.forEach(function(neighbour,i){
var value = graph._assoc_mat[node][neighbour] || 1;
if(node == neighbour)
value *= 2;
weight += value;
});
return weight;
};
function get_neighbours_of_node(graph, node){
if(typeof graph._assoc_mat[node] == 'undefined')
return [];
var neighbours = Object.keys(graph._assoc_mat[node]);
return neighbours;
}
function get_edge_weight(graph, node1, node2){
return graph._assoc_mat[node1] ? graph._assoc_mat[node1][node2] : undefined;
}
function get_graph_size(graph){
var size = 0;
graph.edges.forEach(function(edge){
size += edge.weight;
});
return size;
}
function add_edge_to_graph(graph, edge){
update_assoc_mat(graph, edge);
var edge_index = graph.edges.map(function(d){
return d.source+'_'+d.target;
}).indexOf(edge.source+'_'+edge.target);
if(edge_index != -1)
graph.edges[edge_index].weight = edge.weight;
else
graph.edges.push(edge);
}
function make_assoc_mat(edge_list){
var mat = {};
edge_list.forEach(function(edge, i){
mat[edge.source] = mat[edge.source] || {};
mat[edge.source][edge.target] = edge.weight;
mat[edge.target] = mat[edge.target] || {};
mat[edge.target][edge.source] = edge.weight;
});
return mat;
}
function update_assoc_mat(graph, edge){
graph._assoc_mat[edge.source] = graph._assoc_mat[edge.source] || {};
graph._assoc_mat[edge.source][edge.target] = edge.weight;
graph._assoc_mat[edge.target] = graph._assoc_mat[edge.target] || {};
graph._assoc_mat[edge.target][edge.source] = edge.weight;
}
function clone(obj){
if(obj == null || typeof(obj) != 'object')
return obj;
var temp = obj.constructor();
for(var key in obj)
temp[key] = clone(obj[key]);
return temp;
}
//Core-Algorithm Related
function init_status(graph, status, part){
status['nodes_to_com'] = {};
status['total_weight'] = 0;
status['internals'] = {};
status['degrees'] = {};
status['gdegrees'] = {};
status['loops'] = {};
status['total_weight'] = get_graph_size(graph);
if(typeof part == 'undefined'){
graph.nodes.forEach(function(node,i){
status.nodes_to_com[node] = i;
var deg = get_degree_for_node(graph, node);
if (deg < 0)
throw 'Bad graph type, use positive weights!';
status.degrees[i] = deg;
status.gdegrees[node] = deg;
status.loops[node] = get_edge_weight(graph, node, node) || 0;
status.internals[i] = status.loops[node];
});
}else{
graph.nodes.forEach(function(node,i){
var com = part[node];
status.nodes_to_com[node] = com;
var deg = get_degree_for_node(graph, node);
status.degrees[com] = (status.degrees[com] || 0) + deg;
status.gdegrees[node] = deg;
var inc = 0.0;
var neighbours = get_neighbours_of_node(graph, node);
neighbours.forEach(function(neighbour, i){
var weight = graph._assoc_mat[node][neighbour];
if (weight <= 0){
throw "Bad graph type, use positive weights";
}
if(part[neighbour] == com){
if (neighbour == node){
inc += weight;
}else{
inc += weight/2.0;
}
}
});
status.internals[com] = (status.internals[com] || 0) + inc;
});
}
}
function __modularity(status){
var links = status.total_weight;
var result = 0.0;
var communities = make_set(obj_values(status.nodes_to_com));
communities.forEach(function(com,i){
var in_degree = status.internals[com] || 0 ;
var degree = status.degrees[com] || 0 ;
if(links > 0){
result = result + in_degree / links - Math.pow((degree / (2.0*links)), 2);
}
});
return result;
}
function __neighcom(node, graph, status){
// compute the communities in the neighb. of the node, with the graph given by
// node_to_com
var weights = {};
var neighboorhood = get_neighbours_of_node(graph, node);//make iterable;
neighboorhood.forEach(function(neighbour, i){
if(neighbour != node){
var weight = graph._assoc_mat[node][neighbour] || 1;
var neighbourcom = status.nodes_to_com[neighbour];
weights[neighbourcom] = (weights[neighbourcom] || 0) + weight;
}
});
return weights;
}
function __insert(node, com, weight, status){
//insert node into com and modify status
status.nodes_to_com[node] = +com;
status.degrees[com] = (status.degrees[com] || 0) + (status.gdegrees[node]||0);
status.internals[com] = (status.internals[com] || 0) + weight + (status.loops[node]||0);
}
function __remove(node, com, weight, status){
//remove node from com and modify status
status.degrees[com] = ((status.degrees[com] || 0) - (status.gdegrees[node] || 0));
status.internals[com] = ((status.internals[com] || 0) - weight -(status.loops[node] ||0));
status.nodes_to_com[node] = -1;
}
function __renumber(dict){
var count = 0;
var ret = clone(dict); //deep copy :)
var new_values = {};
var dict_keys = Object.keys(dict);
dict_keys.forEach(function(key){
var value = dict[key];
var new_value = typeof new_values[value] =='undefined' ? -1 : new_values[value];
if(new_value == -1){
new_values[value] = count;
new_value = count;
count = count + 1;
}
ret[key] = new_value;
});
return ret;
}
function __one_level(graph, status){
//Compute one level of the Communities Dendogram.
var modif = true,
nb_pass_done = 0,
cur_mod = __modularity(status),
new_mod = cur_mod;
while (modif && nb_pass_done != __PASS_MAX){
cur_mod = new_mod;
modif = false;
nb_pass_done += 1
graph.nodes.forEach(function(node,i){
var com_node = status.nodes_to_com[node];
var degc_totw = (status.gdegrees[node] || 0) / (status.total_weight * 2.0);
var neigh_communities = __neighcom(node, graph, status);
__remove(node, com_node, (neigh_communities[com_node] || 0.0), status);
var best_com = com_node;
var best_increase = 0;
var neigh_communities_entries = Object.keys(neigh_communities);//make iterable;
neigh_communities_entries.forEach(function(com,i){
var incr = neigh_communities[com] - (status.degrees[com] || 0.0) * degc_totw;
if (incr > best_increase){
best_increase = incr;
best_com = com;
}
});
__insert(node, best_com, neigh_communities[best_com] || 0, status);
if(best_com != com_node)
modif = true;
});
new_mod = __modularity(status);
if(new_mod - cur_mod < __MIN)
break;
}
}
function induced_graph(partition, graph){
var ret = {nodes:[], edges:[], _assoc_mat: {}};
var w_prec, weight;
//add nodes from partition values
var partition_values = obj_values(partition);
ret.nodes = ret.nodes.concat(make_set(partition_values)); //make set
graph.edges.forEach(function(edge,i){
weight = edge.weight || 1;
var com1 = partition[edge.source];
var com2 = partition[edge.target];
w_prec = (get_edge_weight(ret, com1, com2) || 0);
var new_weight = (w_prec + weight);
add_edge_to_graph(ret, {'source': com1, 'target': com2, 'weight': new_weight});
});
return ret;
}
function partition_at_level(dendogram, level){
var partition = clone(dendogram[0]);
for(var i = 1; i < level + 1; i++ )
Object.keys(partition).forEach(function(key,j){
var node = key;
var com = partition[key];
partition[node] = dendogram[i][com];
});
return partition;
}
function generate_dendogram(graph, part_init){
if(graph.edges.length == 0){
var part = {};
graph.nodes.forEach(function(node,i){
part[node] = node;
});
return part;
}
var status = {};
init_status(original_graph, status, part_init);
var mod = __modularity(status);
var status_list = [];
__one_level(original_graph, status);
var new_mod = __modularity(status);
var partition = __renumber(status.nodes_to_com);
status_list.push(partition);
mod = new_mod;
var current_graph = induced_graph(partition, original_graph);
init_status(current_graph, status);
while (true){
__one_level(current_graph, status);
new_mod = __modularity(status);
if(new_mod - mod < __MIN)
break;
partition = __renumber(status.nodes_to_com);
status_list.push(partition);
mod = new_mod;
current_graph = induced_graph(partition, current_graph);
init_status(current_graph, status);
}
return status_list;
}
var core = function(){
var status = {};
var dendogram = generate_dendogram(original_graph, partition_init);
return partition_at_level(dendogram, dendogram.length - 1);
};
core.nodes = function(nds){
if(arguments.length > 0){
original_graph_nodes = nds;
}
return core;
};
core.edges = function(edgs){
if(typeof original_graph_nodes == 'undefined')
throw 'Please provide the graph nodes first!';
if(arguments.length > 0){
original_graph_edges = edgs;
var assoc_mat = make_assoc_mat(edgs);
original_graph = { 'nodes': original_graph_nodes,
'edges': original_graph_edges,
'_assoc_mat': assoc_mat };
}
return core;
};
core.partition_init = function(prttn){
if(arguments.length > 0){
partition_init = prttn;
}
return core;
};
return core;
}
})();

getting html input value inside javascript class

i am new to javascript and im making a BMI calculator. im making a class in javascript to produce the calculations. currently users could input their height (in feet and inches) and weight. when i run a method within my class. it keeps saying this.feet = null instead of grabbing the value from the input. my javascript code is below. result() is in my html for the submit button.
function calculator(feet,inches,weight) {
this.feet = feet.value;
this.inches = inches.value;
this.weight = weight.value;
this.validateInput = function() {
var errors = [];
if(isNaN(this.feet) || this.feet < 0) {
errors.push("Feet");
}
else {
return this.feet
};
if(isNaN(this.inches) || this.inches < 0 || this.inches > 11) {
errors.push("Inches")
}
else {
return this.inches;
};
if(isNaN(this.weight) || this.weight < 0) {
errors.push("Weight");
}
else {
return this.weight
}
};
this.inchesConverter = function() {
this.feet = parseFloat(feet);
this.inches = parseFloat(inches);
return parseInt(this.feet*12+this.inches);
};
this.bmi = function() {
var height = this.inchesConverter();
var validater = this.validateInput();
for(r = 0; r < errors.length; r++){
if(errors.length > 0) {
return errors[r] + " must be a valid positive number.";
}
else {
parseFloat((validateWeight * 703) / (Math.pow(height, 2))).toFixed(1);
}
}
};
};
var getWeight = document.getElementById('txtWeight');
var getFeet = document.getElementById('txtHeightFeet');
var getInches = document.getElementById('txtHeightInches');
var test = new calculator(getFeet, getInches, getWeight);
function result() {
document.getElementById("lblBMI").innerHTML(test.bmi());
}
Instead of assigning feet.value to this.feet try assigning feet.getAttribute('value')
If you console.log(feet) does it show the proper DOM element?
There is no need to declare the variables with "this."
function calculator(paraFeet,paraInches,paraWeight) {
var feet = paraFeet.value;
var inches = paraInches.value;
var weight = paraWeight.value;
...
you can now remove "this." from every of these variables inside your function
Every browser has JavaScript console on which you can debug your code.
I have some fun to fix it here or there but also you should try it yourself.
Anyway here it is:
function calculator(weight, feet, inches) {
this.weight = weight;
this.feet = feet;
this.inches = inches;
this.validateInput = function() {
var errors = [];
if (!this.validNumber(this.weight, 1000)) {
errors.push("Invalid weight.");
}
if (!this.validNumber(this.feet, 10)) {
errors.push("Invalid hight in feet.");
}
if (!this.validNumber(this.inches, 11)) {
errors.push("Invalid hight in inches.")
}
return errors;
};
this.validNumber = function(num, max) {
if (num.length > 0 && !isNaN(num)) {
var number = parseInt(num);
return number > 0 && number < max + 1;
}
return false;
}
this.displayErrors = function(errors) {
var html = "";
for (error of errors)
html += error + "<br/>";
return html;
};
this.inchesConverter = function() {
var feet = parseInt(this.feet);
var inches = parseInt(this.inches);
return feet * 12 + inches;
};
this.bmi = function() {
var errors = this.validateInput();
if (errors.length > 0) {
return this.displayErrors(errors);
}
var height = this.inchesConverter();
return parseFloat((this.weight * 703) / (Math.pow(height, 2))).toFixed(1);
};
};
function result() {
var getWeight = document.getElementById('txtWeight').value;
var getFeet = document.getElementById('txtHeightFeet').value;
var getInches = document.getElementById('txtHeightInches').value;
var test = new calculator(getWeight, getFeet, getInches);
document.getElementById("lblBMI").innerHTML = test.bmi();
return false;
}
<span>
<label>Weight</label>
<input id="txtWeight">
</span>
<span>
<label>HeightFeet</label>
<input id="txtHeightFeet">
</span>
<span>
<label>HeightInches</label>
<input id="txtHeightInches">
</span>
<button id='run' onClick="return result();">Calculate</button>
<div id="lblBMI"></div>
Figured out what my issue was. The problem arose from my for loop. Working code is posted below!
function calculator(feet,inches,weight) {
this.feet = feet.value;
this.inches = inches.value;
this.weight = weight.value;
this.validateInput = function() {
var errors = [];
if(isNaN(this.feet) || this.feet < 0 || this.feet == "") {
errors.push("feet");
};
if(isNaN(this.inches) || this.inches < 0 || this.inches > 11) {
errors.push("inches")
};
if(isNaN(this.weight) || this.weight < 0 || this.weight == "") {
errors.push("weight");
};
return errors;
console.log(errors);
};
this.inchesConverter = function() {
var parseFeet = parseFloat(this.feet);
var parseInches = parseFloat(this.inches);
return parseInt(parseFeet*12+parseInches);
};
this.bmi = function() {
var height = this.inchesConverter();
var errors = this.validateInput();
if(errors.length > 0) {
for(r = 0; r < errors.length; r++){
return "Please enter a correct number for " + errors[r];
};
}
else {
return parseFloat((this.weight * 703) / (Math.pow(height, 2))).toFixed(1);
};
};
};
function result(){
var getWeight = document.getElementById('txtWeight');
var getFeet = document.getElementById('txtHeightFeet');
var getInches = document.getElementById('txtHeightInches');
var test = new calculator(getFeet, getInches, getWeight);
document.getElementById("lblBMI").innerHTML = test.bmi();
};

Unreachable code in varien/configurable.js Magento

I was taking a look at the Magento source file to try to understand why I can't move varien/configurable.js whithout throwing an error with another extension, so Google Closure Compiler to shrink it, but it returns an error at line 267:
JSC_UNREACHABLE_CODE: unreachable code at line 267 character 8
if($('product-price-'+this.config.productId)){ ^
In particular these is the slice of code:
getAttributeOptions: function(attributeId){
if(this.config.attributes[attributeId]){
return this.config.attributes[attributeId].options;
}
},
Could someone explain me why it throw out that warning?
This is the whole code:
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE_AFL.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license#magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* #category Varien
* #package js
* #copyright Copyright (c) 2014 Magento Inc. (http://www.magentocommerce.com)
* #license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
*/
if (typeof Product == 'undefined') {
var Product = {};
}
/**************************** CONFIGURABLE PRODUCT **************************/
Product.Config = Class.create();
Product.Config.prototype = {
initialize: function(config){
this.config = config;
this.taxConfig = this.config.taxConfig;
if (config.containerId) {
this.settings = $$('#' + config.containerId + ' ' + '.super-attribute-select');
} else {
this.settings = $$('.super-attribute-select');
}
this.state = new Hash();
this.priceTemplate = new Template(this.config.template);
this.prices = config.prices;
// Set default values from config
if (config.defaultValues) {
this.values = config.defaultValues;
}
// Overwrite defaults by url
var separatorIndex = window.location.href.indexOf('#');
if (separatorIndex != -1) {
var paramsStr = window.location.href.substr(separatorIndex+1);
var urlValues = paramsStr.toQueryParams();
if (!this.values) {
this.values = {};
}
for (var i in urlValues) {
this.values[i] = urlValues[i];
}
}
// Overwrite defaults by inputs values if needed
if (config.inputsInitialized) {
this.values = {};
this.settings.each(function(element) {
if (element.value) {
var attributeId = element.id.replace(/[a-z]*/, '');
this.values[attributeId] = element.value;
}
}.bind(this));
}
// Put events to check select reloads
this.settings.each(function(element){
Event.observe(element, 'change', this.configure.bind(this))
}.bind(this));
// fill state
this.settings.each(function(element){
var attributeId = element.id.replace(/[a-z]*/, '');
if(attributeId && this.config.attributes[attributeId]) {
element.config = this.config.attributes[attributeId];
element.attributeId = attributeId;
this.state[attributeId] = false;
}
}.bind(this))
// Init settings dropdown
var childSettings = [];
for(var i=this.settings.length-1;i>=0;i--){
var prevSetting = this.settings[i-1] ? this.settings[i-1] : false;
var nextSetting = this.settings[i+1] ? this.settings[i+1] : false;
if (i == 0){
this.fillSelect(this.settings[i])
} else {
this.settings[i].disabled = true;
}
$(this.settings[i]).childSettings = childSettings.clone();
$(this.settings[i]).prevSetting = prevSetting;
$(this.settings[i]).nextSetting = nextSetting;
childSettings.push(this.settings[i]);
}
// Set values to inputs
this.configureForValues();
document.observe("dom:loaded", this.configureForValues.bind(this));
},
configureForValues: function () {
if (this.values) {
this.settings.each(function(element){
var attributeId = element.attributeId;
element.value = (typeof(this.values[attributeId]) == 'undefined')? '' : this.values[attributeId];
this.configureElement(element);
}.bind(this));
}
},
configure: function(event){
var element = Event.element(event);
this.configureElement(element);
},
configureElement : function(element) {
this.reloadOptionLabels(element);
if(element.value){
this.state[element.config.id] = element.value;
if(element.nextSetting){
element.nextSetting.disabled = false;
this.fillSelect(element.nextSetting);
this.resetChildren(element.nextSetting);
}
}
else {
this.resetChildren(element);
}
this.reloadPrice();
},
reloadOptionLabels: function(element){
var selectedPrice;
if(element.options[element.selectedIndex].config && !this.config.stablePrices){
selectedPrice = parseFloat(element.options[element.selectedIndex].config.price)
}
else{
selectedPrice = 0;
}
for(var i=0;i<element.options.length;i++){
if(element.options[i].config){
element.options[i].text = this.getOptionLabel(element.options[i].config, element.options[i].config.price-selectedPrice);
}
}
},
resetChildren : function(element){
if(element.childSettings) {
for(var i=0;i<element.childSettings.length;i++){
element.childSettings[i].selectedIndex = 0;
element.childSettings[i].disabled = true;
if(element.config){
this.state[element.config.id] = false;
}
}
}
},
fillSelect: function(element){
var attributeId = element.id.replace(/[a-z]*/, '');
var options = this.getAttributeOptions(attributeId);
this.clearSelect(element);
element.options[0] = new Option('', '');
element.options[0].innerHTML = this.config.chooseText;
var prevConfig = false;
if(element.prevSetting){
prevConfig = element.prevSetting.options[element.prevSetting.selectedIndex];
}
if(options) {
var index = 1;
for(var i=0;i<options.length;i++){
var allowedProducts = [];
if(prevConfig) {
for(var j=0;j<options[i].products.length;j++){
if(prevConfig.config.allowedProducts
&& prevConfig.config.allowedProducts.indexOf(options[i].products[j])>-1){
allowedProducts.push(options[i].products[j]);
}
}
} else {
allowedProducts = options[i].products.clone();
}
if(allowedProducts.size()>0){
options[i].allowedProducts = allowedProducts;
element.options[index] = new Option(this.getOptionLabel(options[i], options[i].price), options[i].id);
if (typeof options[i].price != 'undefined') {
element.options[index].setAttribute('price', options[i].price);
}
element.options[index].config = options[i];
index++;
}
}
}
},
getOptionLabel: function(option, price){
var price = parseFloat(price);
if (this.taxConfig.includeTax) {
var tax = price / (100 + this.taxConfig.defaultTax) * this.taxConfig.defaultTax;
var excl = price - tax;
var incl = excl*(1+(this.taxConfig.currentTax/100));
} else {
var tax = price * (this.taxConfig.currentTax / 100);
var excl = price;
var incl = excl + tax;
}
if (this.taxConfig.showIncludeTax || this.taxConfig.showBothPrices) {
price = incl;
} else {
price = excl;
}
var str = option.label;
if(price){
if (this.taxConfig.showBothPrices) {
str+= ' ' + this.formatPrice(excl, true) + ' (' + this.formatPrice(price, true) + ' ' + this.taxConfig.inclTaxTitle + ')';
} else {
str+= ' ' + this.formatPrice(price, true);
}
}
return str;
},
formatPrice: function(price, showSign){
var str = '';
price = parseFloat(price);
if(showSign){
if(price<0){
str+= '-';
price = -price;
}
else{
str+= '+';
}
}
var roundedPrice = (Math.round(price*100)/100).toString();
if (this.prices && this.prices[roundedPrice]) {
str+= this.prices[roundedPrice];
}
else {
str+= this.priceTemplate.evaluate({price:price.toFixed(2)});
}
return str;
},
clearSelect: function(element){
for(var i=element.options.length-1;i>=0;i--){
element.remove(i);
}
},
getAttributeOptions: function(attributeId){
if(this.config.attributes[attributeId]){
return this.config.attributes[attributeId].options;
}
},
reloadPrice: function(){
if (this.config.disablePriceReload) {
return;
}
var price = 0;
var oldPrice = 0;
for(var i=this.settings.length-1;i>=0;i--){
var selected = this.settings[i].options[this.settings[i].selectedIndex];
if(selected.config){
price += parseFloat(selected.config.price);
oldPrice += parseFloat(selected.config.oldPrice);
}
}
optionsPrice.changePrice('config', {'price': price, 'oldPrice': oldPrice});
optionsPrice.reload();
return price;
if($('product-price-'+this.config.productId)){
$('product-price-'+this.config.productId).innerHTML = price;
}
this.reloadOldPrice();
},
reloadOldPrice: function(){
if (this.config.disablePriceReload) {
return;
}
if ($('old-price-'+this.config.productId)) {
var price = parseFloat(this.config.oldPrice);
for(var i=this.settings.length-1;i>=0;i--){
var selected = this.settings[i].options[this.settings[i].selectedIndex];
if(selected.config){
price+= parseFloat(selected.config.price);
}
}
if (price < 0)
price = 0;
price = this.formatPrice(price);
if($('old-price-'+this.config.productId)){
$('old-price-'+this.config.productId).innerHTML = price;
}
}
}
}
Please check the below code in reloadOldPrice function:
return price;
if($('product-price-'+this.config.productId)){
$('product-price-'+this.config.productId).innerHTML = price;
}
this.reloadOldPrice();
when you are using return price; the return statement doesn't allow next code to run. So its unreachable, hence garbage.
Either use some condition if you want the function to stop there in specific situations or put that return statement at the end of function or simply remove return price; if its not required.

Categories