Troubleshoot with JS - javascript

I have been looking over a JS and HTML for my friend, because it doesn't work, and I have spent 5 hours on it, and I can't stil find the error...
When you test the code in jsfiddle, try to click on "Bountie", it should take HP from you, but it doesn't, it does nothing...
Im sorry for the long code.
Demo
/*
Variables
Started at 10:57 1/2-16
Finished at unknown
*/
//Level variables
var level = 1;
var gon = 0;
var xp = 0;
var sp = 3;
//Item variables
var items = 0;
var key = 0;
var gem = 0;
var stone = 0;
//Token system
var token = 0;
var heatf = 0;
var heltf = 0;
//Quest system
var bountieqp = 0;
var mapqp = 10;
var hellqp = 10;
var heavenqp = 10;
var underworldqp = 10;
//Quest tracker
var bountieqtracker = 0;
var mapqtracker = 0;
var hellqtracker = 0;
var heavenqtracker = 0;
var underworldqtracker = 0;
//Predium varables
var giftbox = 1;
//Combats variables
var str = 0;
var dex = 0;
var intt = 0;
var armor = 4;
var dmg = 5;
var hp = 300;
var hpren = 3;
var mana = 60;
var manaren = 1;
//Addon variables
var xpbonus = 1;
var xponkill = 0;
var mf = 1;
var souls = 0;
//Prestige system
var prelevel = 1;
var ppiece = 0;
//Map tracker variables
var bountietracker = 0;
var maptracker = 0;
var gmaptracker = 0;
var helltracker = 0;
var heaventracker = 0;
var underworldtracker = 0;
//Quest system updates
document.getElementById('hellqp').innerHTML = hellqp;
document.getElementById('heavenqp').innerHTML = heavenqp;
document.getElementById('bountieqp').innerHTML = bountieqp;
document.getElementById('mapqp').innerHTML = mapqp;
document.getElementById('underworldqp').innerHTML = underworldqp;
//Tracker system updates
document.getElementById('maptracker').innerHTML = maptracker;
document.getElementById('underworldtracker').innerHTML = underworldtracker;
document.getElementById('gmaptracker').innerHTML = gmaptracker;
document.getElementById('bountietracker').innerHTML = bountietracker;
document.getElementById('helltracker').innerHTML = helltracker;
document.getElementById('heaventracker').innerHTML = heaventracker;
//Quest tracker system updates
document.getElementById('mapqtracker').innerHTML = mapqtracker;
document.getElementById('underworldqtracker').innerHTML = underworldqtracker;
document.getElementById('bountieqtracker').innerHTML = bountieqtracker;
document.getElementById('hellqtracker').innerHTML = hellqtracker;
document.getElementById('heavenqtracker').innerHTML = heavenqtracker;
//Stats system updates
document.getElementById('sp').innerHTML = sp;
document.getElementById('dex').innerHTML = dex;
document.getElementById('str').innerHTML = str;
document.getElementById('intt').innerHTML = intt;
document.getElementById('dmg').innerHTML = dmg;
document.getElementById('hp').innerHTML = hp;
document.getElementById('mana').innerHTML = mana;
document.getElementById('armor').innerHTML = armor;
document.getElementById('hpren').innerHTML = hpren;
document.getElementById('manaren').innerHTML = manaren;
//Addon system updates
document.getElementById('giftbox').innerHTML = giftbox;
document.getElementById('souls').innerHTML = souls;
document.getElementById('xponkill').innerHTML = xponkill;
document.getElementById('xpbonus').innerHTML = xpbonus;
document.getElementById('mf').innerHTML = mf;
//Items system updates
document.getElementById('key').innerHTML = key;
document.getElementById('stone').innerHTML = stone;
document.getElementById('gem').innerHTML = gem;
document.getElementById('items').innerHTML = items;
document.getElementById('token').innerHTML = token;
document.getElementById('heatf').innerHTML = heatf;
document.getElementById('heltf').innerHTML = heltf;
//Level system updates
document.getElementById('level').innerHTML = level;
document.getElementById('gon').innerHTML = gon;
document.getElementById('xp').innerHTML = xp;
/*
Test selection
*/
/*
Predium Addons
Started at 14:10 1/2-16
Finished at
*/
function openBox() {
var boxrand = Math.floor(Math.random() * (13 - 1 + 1)) + 1;
var gembrand = Math.floor(Math.random() * (5 - 1 + 1)) + 1;
var itemsbrand = Math.floor(Math.random() * (100 - 1 + 1)) + 1;
var keybrand = Math.floor(Math.random() * (20 - 1 + 1)) + 1;
var stonebrand = Math.floor(Math.random() * (10 - 1 + 1)) + 1;
var bountieqpbrand = Math.floor(Math.random() * (9 - 1 + 1)) + 1;
var mapqpbrand = Math.floor(Math.random() * (9 - 1 + 1)) + 1;
var hellqpbrand = Math.floor(Math.random() * (9 - 1 + 1)) + 1;
var heavenqpbrand = Math.floor(Math.random() * (9 - 1 + 1)) + 1;
var underworldqpbrand = Math.floor(Math.random() * (9 - 1 + 1)) + 1;
var heltfrand = Math.floor(Math.random() * (3 - 1 + 1)) + 1;
var heabrand = Math.floor(Math.random() * (3 - 1 + 1)) + 1;
var xpbrand = Math.floor(Math.random() * (500000 - 1 + 1)) + 1;
if (boxrand == 1) {
gem = gem + gembrand;
document.getElementById('gem').innerHTML = gem;
} else if (boxrand == 2) {
items = items + itemsbrand;
document.getElementById('items').innerHTML = items;
}else if (boxrand == 3) {
key = key + keybrand;
document.getElementById('key').innerHTML = key;
}else if (boxrand == 4) {
stone = stone + stonebrand;
document.getElementById('stone').innerHTML = stone;
}else if (boxrand == 5) {
bountieqp = bountieqp + bountieqpbrand;
document.getElementById('bountieqp').innerHTML = bountieqp;
}else if (boxrand == 6) {
mapqp = mapqp + mapqpbrand;
document.getElementById('mapqp').innerHTML = mapqp;
}else if (boxrand == 7) {
hellqp = hellqp + hellqpbrand;
document.getElementById('hellqp').innerHTML = hellqp;
} else if (boxrand == 8) {
heavenqp = heavenqp + heavenqpbrand;
document.getElementById('heavenqp').innerHTML = heavenqp;
} else if (boxrand == 9) {
underworldqp = underworldqp + underworldqpbrand;
document.getElementById('underworldqp').innerHTML = underworldqp;
} else if(boxrand == 10) {
heltf = heltf + heltfbrand;
document.getElementById('heltf').innerHTML = heltf;
} else if(boxrand == 11) {
heatf = heatf + heatfbrand;
document.getElementById('heatf').innerHTML = heatf;
} else if(boxrand == 12) {
xp = xp + xpbrand;
document.getElementById('xp').innerHTML = xp;
} else if (boxrand == 13) {
ppiece = ppiece + ppiecebrand;
document.getElementById('ppiece').innerHTML = ppiece;
}
}
function gbChecker() {
if (giftbox >= 1) {
openBox();
giftbox = giftbox - 1;
document.getElementById('giftbox').innerHTML = giftbox;
} else {
alert('You dont have a Mystery Box!');
}
}
/*
Level
Started at 11:46 1/2-16
Finished at
*/
function levelUp() {
var levelCost = Math.floor(200 * Math.pow(1.1,level));
if (xp >= levelCost){
level = level + 1;
xp = xp - levelCost;
sp = sp + 3;
document.getElementById('level').innerHTML = level;
document.getElementById('xp').innerHTML = xp;
document.getElementById('sp').innerHTML = sp;
}
var nextlevelCost = Math.floor(200 * Math.pow(1.1,level));
document.getElementById('levelCost').innerHTML = nextlevelCost;
}
function gonUp() {
var gonCost = Math.floor(200 * Math.pow(1.1,gon));
if (xp >= gonCost) {
gon = gon + 1;
xp = xp - gonCost;
sp = sp + 1;
document.getElementById('gon').innerHTML = gon;
document.getElementById('xp').innerHTML = xp;
document.getElementById('sp').innerHTML = sp;
}
var nextgonCost = Math.floor(200 * Math.pow(1.1,gon));
document.getElementById('gonCost').innerHTML = nextgonCost;
}
function levelChecker() {
if (level == 120) {
gonUp();
} else {
levelUp();
}
}
/*
Addon Makers
Started at 11:34 1/2-16
Finished at 12:42 1/2-16
*/
function pp256Maker() {
var pp256rand = Math.floor(Math.random() * (256 - 1 + 1)) + 1;
if (pp256rand == 1) {
ppiece = ppiece + (1 * mf);
document.getElementById('ppiece').innerHTML = ppiece;
}
}
function gb256Maker() {
var gb256rand = Math.floor(Math.random() * (256 - 1 + 1)) + 1;
if (gb256rand == 1) {
giftbox = giftbox + 1;
document.getElementById('giftbox').innerHTML = giftbox;
}
}
function pp128Maker() {
var pp128rand = Math.floor(Math.random() * (128 - 1 + 1)) + 1;
if (pp128rand == 1) {
ppiece = ppiece + (1 * mf);
document.getElementById('ppiece').innerHTML = ppiece;
}
}
function gb128Maker() {
var gb128rand = Math.floor(Math.random() * (128 - 1 + 1)) + 1;
if (gb128rand == 1) {
giftbox = giftbox + 1;
document.getElementById('giftbox').innerHTML = giftbox;
}
}
function pp25Maker() {
var pp25rand = Math.floor(Math.random() * (25 - 1 + 1)) + 1;
if (pp25rand == 1) {
ppiece = ppiece + (1 * mf);
document.getElementById('ppiece').innerHTML = ppiece;
}
}
function gb64Maker() {
var gb64rand = Math.floor(Math.random() * (64 - 1 + 1)) + 1;
if (gb64rand == 1) {
giftbox = giftbox + 1;
document.getElementById('giftbox').innerHTML = giftbox;
}
}
function pp17Maker() {
var pp17rand = Math.floor(Math.random() * (17 - 1 + 1)) + 1;
if (pp17rand == 1) {
ppiece = ppiece + (1 * mf);
document.getElementById('ppiece').innerHTML = ppiece;
}
}
function gb32Maker() {
var gb32rand = Math.floor(Math.random() * (32 - 1 + 1)) + 1;
if (gb32rand == 1) {
giftbox = giftbox + 1;
document.getElementById('giftbox').innerHTML = giftbox;
}
}
function pp5Maker() {
var pp5rand = Math.floor(Math.random() * (5 - 1 + 1)) + 1;
if (pp5rand == 1) {
ppiece = ppiece + (1 * mf);
document.getElementById('ppiece').innerHTML = ppiece;
}
}
function gb10Maker() {
var gb10rand = Math.floor(Math.random() * (10 - 1 + 1)) + 1;
if (gb10rand == 1) {
giftbox = giftbox + 1;
document.getElementById('giftbox').innerHTML = giftbox;
}
}
function gb16Maker() {
var gb16rand = Math.floor(Math.random() * (16 - 1 + 1)) + 1;
if (gb16rand == 1) {
giftbox = giftbox + 1;
document.getElementById('giftbox').innerHTML = giftbox;
}
}
function gb5Maker() {
var gb5rand = Math.floor(Math.random() * (5 - 1 + 1)) + 1;
if (gb5rand == 1) {
giftbox = giftbox + 1;
document.getElementById('giftbox').innerHTML = giftbox;
}
}
/*
Quest Makers
Started at 12:43 1/2-16
Finished at 12:47 1/2-16
*/
function bountieqpMaker() {
var bountieqprand = Math.floor(Math.random() * (10 - 1 + 1)) + 1;
if (bountieqprand == 1) {
bountieqp = bountieqp + (1 * mf);
document.getElementById('bountieqp').innerHTML = bountieqp;
}
}
function mapqpMaker() {
var mapqprand = Math.floor(Math.random() * (10 - 1 + 1)) + 1;
if (mapqprand == 1) {
map = map + (1 * mf);
document.getElementById('mapqp').innerHTML = mapqp;
}
}
function hellqpMaker() {
var bountieqprand = Math.floor(Math.random() * (10 - 1 + 1)) + 1;
if (hellqprand == 1) {
hell = hell + (1 * mf);
document.getElementById('hellqp').innerHTML = hellqp;
}
}
function heavenqpMaker() {
var heavenqprand = Math.floor(Math.random() * (10 - 1 + 1)) + 1;
if (heavenqprand == 1) {
heavenqp = heavenqp + (1 * mf);
document.getElementById('heavenqp').innerHTML = heavenqp;
}
}
function underworldqpMaker() {
var underworldqprand = Math.floor(Math.random() * (10 - 1 + 1)) + 1;
if (underworldqprand == 1) {
underworldqp = underworldqp + (1 * mf);
document.getElementById('underworldqp').innerHTML = underworldqp;
}
}
/*
Req items Maker
Started at 12:44 1/2-16
Finished at 13:17 1/2-16
*/
function keyMaker() {
var keyrand = Math.floor(Math.random() * (10 - 1 + 1)) + 1;
if (keyrand == 1) {
key = key + (1 * mf);
document.getElementById('key').innerHTML = key;
}
}
function stoneMaker(){
var stonerand = Math.floor(Math.random() * (5 - 1 + 1)) + 1;
if (stonerand == 1) {
stone = stone + (1 * mf);
document.getElementById('stone').innerHTML = stone;
}
}
/*
Quest completing
Started at 13:17 1/2-16
Finished at 13:45 1/2-16
*/
function bouqChecker(){
if (bountieqp >= 10) {
bouQuest();
} else {
alert('You dont have 10 Bountie quest pieces!. You only have ' + bountieqp + '!');
}
}
function mapqChecker(){
if (mapqp >= 10) {
mapQuest();
} else {
alert('You dont have 10 Map quest pieces!. You only have ' + mapqp + '!');
}
}
function hellqChecker(){
if (hellqp >= 10) {
hellQuest();
} else {
alert('You dont have 10 Hell quest pieces!. You only have ' + hellqp + '!');
}
}
function heavenqChecker(){
if(heavenqp >= 10){
heavenQuest();
}else{
alert('You dont have 10 Heaven quest pieces!. You only have ' + heavenqp + '!');
}
}
function underworldqChecker(){
if(underworldqp >= 10){
underworldQuest();
}else{
alert('You dont have 10 Underworld quest pieces!. You only have ' + underworldqp + '!');
}
}
function bouQuest(){
var bouqxprand = Math.floor(Math.random() * (1000 - 200 + 200)) + 1;
xp = xp + ((bouqxprand * xpbonus) * prelevel);
bountieqp = bountieqp - 10;
gb128Maker();
document.getElementById('xp').innerHTML = xp;
document.getElementById('bountieqp').innerHTML = bountieqp;
}
function mapQuest(){
var mapqxprand = Math.floor(Math.random() * (4500 - 850 + 850)) + 1;
xp = xp + ((mapqxprand * xpbonus) * prelevel);
mapqp = mapqp - 10;
gb64Maker();
document.getElementById('xp').innerHTML = xp;
document.getElementById('mapqp').innerHTML = mapqp;
}
function hellQuest(){
var hellqxprand = Math.floor(Math.random() * (250000 - 50000 + 50000)) + 1;
xp = xp + ((hellqxprand * xpbonus) * prelevel);
hellqp = hellqp - 10;
gb16Maker();
document.getElementById('xp').innerHTML = xp;
document.getElementById('hellqp').innerHTML = hellqp;
}
function heavenQuest(){
var heavenqxprand = Math.floor(Math.random() * (250000 - 50000 + 50000)) + 1;
xp = xp + ((heavenqxprand * xpbonus) * prelevel);
heavenqp = heavenqp - 10;
gb16Maker();
document.getElementById('xp').innerHTML = xp;
document.getElementById('heavenqp').innerHTML = heavenqp;
}
function underworldQuest(){
var underworldqxprand = Math.floor(Math.random() * (1250000 - 500000 + 500000)) + 1;
xp = xp + ((underworldqxprand * xpbonus) * prelevel);
underworldqp = underworldqp - 10;
gb5Maker();
document.getElementById('xp').innerHTML = xp;
document.getElementById('underworldqp').innerHTML = underworldqp;
}
/*
Bountie Map
Started at 11:27 1/2-16
Finished at 13:18 1/2-16
*/
function doBountie() {
var bountieCost = Math.floor(50 * Math.pow(1.006,bountietracker));
var bouxprand = Math.floor(Math.random() * (200 - 20 + 20)) + 1;
var bouitemrand = Math.floor(Math.random() * (5 - 1 + 1)) + 1;
if (dmg + armor >= bountieCost) {
hp = hp - 1;
xp = xp + (((bouxprand + xponkill) * xpbonus) * prelevel);
items = items + (bouitemrand * mf);
bountietracker = bountietracker + 1;
keyMaker();
bountieqpMaker();
pp256Maker();
gb256Maker();
document.getElementById('hp').innerHTML = hp;
document.getElementById('hp2').innerHTML = hp;
document.getElementById('xp').innerHTML = xp;
document.getElementById('items').innerHTML = items;
} else if (hp >= bountieCost) {
hp = hp - (bountieCost - (armor + dmg));
xp = xp + (((bouxprand + xponkill) * xpbonus) * prelevel);
items = items + (bouitemrand* mf);
bountietracker = bountietracker + 1;
keyMaker();
bountieqpMaker();
pp256Maker();
gb256Maker();
document.getElementById('hp').innerHTML = hp;
document.getElementById('xp').innerHTML = xp;
document.getElementById('hp2').innerHTML = hp;
document.getElementById('items').innerHTML = items;
}else{
alert('You dont have enough HP to complete a bountie. Bountie costs ' + bountieCost + ' and you only have ' + hp + '!');
}
var nextbountieCost = Math.floor(50 * Math.pow(1.006,bountietracker));
document.getElementById('bountieCost').innerHTML = nextbountieCost;
}
/*
Map Map
Started at 12:37 1/2-16
Finished at
*/
function doMap(){
var mapCost = Math.floor(300 * Math.pow(1.006,maptracker));
var mapxprand = Math.floor(Math.random() * (850 - 200 + 200)) + 1;
var mapitemrand = Math.floor(Math.random() * (12 - 4 + 4)) + 1;
if(dmg + armor >= mapCost){
hp = hp - 1;
xp = xp + (((mapxprand + xponkill) * xpbonus) * prelevel);
items = items + (mapitemrand * mf);
keyMaker();
gb128Maker();
mapqpMaker();
document.getElementById('hp').innerHTML = hp;
document.getElementById('xp').innerHTML = xp;
document.getElementById('hp2').innerHTML = hp;
document.getElementById('items').innerHTML = items;
}else if(hp >= mapCost){
hp = hp - (mapCost - (armor + dmg));
xp = xp + (((mapxprand + xponkill) * xpbonus) * prelevel);
items = items + (mapitemrand * mf);
keyMaker();
gb128Maker();
mapqpMaker();
document.getElementById('hp').innerHTML = hp;
document.getElementById('xp').innerHTML = xp;
document.getElementById('hp2').innerHTML = hp;
document.getElementById('items').innerHTML = items;
}else if(hp =< mapCost){
alert('You dont have enough HP to complete a Map. Map costs ' + mapCost + ' and you only have ' + hp + '!');
}else{
alert('You dont have a key to open a Map!');
}
var nextmapCost = Math.floor(300 * Math.pow(1.006,maptracker));
document.getElementById('mapCost').innerHTML = nextmapCost;
}

When I click the bountie button, I get the error Uncaught ReferenceError: levelChecker is not defined.
Also, on Line #582
Uncaught SyntaxError: Unexpected token <
if(hp =< mapCost) should be if(hp <= mapCost)
It looks like there are a few Javascript errors in your script. I recommend using Google Chrome's Inspection tool for stepping through your Javascript, using breakpoints to see the data and errors.

Related

JSON Parse issue in React-Native

I'm so lost.
I keep getting this error:
"SAVED SCREEN NETWORK ERROR: , [SyntaxError: JSON Parse error: Unrecognized token '<']
at node_modules/color-string/index.js:90:16 in cs.get.rgb" (Line 90 is right below my console.log in the code down below)
This part:
console.log(match)
if (match[4]) {
if (match[5]) {
rgb[3] = parseFloat(match[4]) * 0.01;
} else {
rgb[3] = parseFloat(match[4]);
}
}
} else if (match = string.match(per)) {
for (i = 0; i < 3; i++) {
rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
}
But when I check the node_modules, I can't understand at all where its even using JSON. I console logged the match and all I'm getting is this:
Array [
"rgb(28, 28, 30)",
"28",
"28",
"30",
undefined,
undefined,
]
I literally don't know what to do anymore, so I'm hoping someone more experienced can help me out on this.
/* MIT license */
var colorNames = require('color-name');
var swizzle = require('simple-swizzle');
var hasOwnProperty = Object.hasOwnProperty;
var reverseNames = {};
// create a list of reverse color names
for (var name in colorNames) {
if (hasOwnProperty.call(colorNames, name)) {
reverseNames[colorNames[name]] = name;
}
}
var cs = module.exports = {
to: {},
get: {}
};
cs.get = function (string) {
var prefix = string.substring(0, 3).toLowerCase();
var val;
var model;
switch (prefix) {
case 'hsl':
val = cs.get.hsl(string);
model = 'hsl';
break;
case 'hwb':
val = cs.get.hwb(string);
model = 'hwb';
break;
default:
val = cs.get.rgb(string);
model = 'rgb';
break;
}
if (!val) {
return null;
}
return {model: model, value: val};
};
cs.get.rgb = function (string) {
if (!string) {
return null;
}
var abbr = /^#([a-f0-9]{3,4})$/i;
var hex = /^#([a-f0-9]{6})([a-f0-9]{2})?$/i;
var rgba = /^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/;
var per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/;
var keyword = /^(\w+)$/;
var rgb = [0, 0, 0, 1];
var match;
var i;
var hexAlpha;
if (match = string.match(hex)) {
hexAlpha = match[2];
match = match[1];
for (i = 0; i < 3; i++) {
// https://jsperf.com/slice-vs-substr-vs-substring-methods-long-string/19
var i2 = i * 2;
rgb[i] = parseInt(match.slice(i2, i2 + 2), 16);
}
if (hexAlpha) {
rgb[3] = parseInt(hexAlpha, 16) / 255;
}
} else if (match = string.match(abbr)) {
match = match[1];
hexAlpha = match[3];
for (i = 0; i < 3; i++) {
rgb[i] = parseInt(match[i] + match[i], 16);
}
if (hexAlpha) {
rgb[3] = parseInt(hexAlpha + hexAlpha, 16) / 255;
}
} else if (match = string.match(rgba)) {
for (i = 0; i < 3; i++) {
rgb[i] = parseInt(match[i + 1], 0);
}
console.log(match)
if (match[4]) {
if (match[5]) {
rgb[3] = parseFloat(match[4]) * 0.01;
} else {
rgb[3] = parseFloat(match[4]);
}
}
} else if (match = string.match(per)) {
for (i = 0; i < 3; i++) {
rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
}
if (match[4]) {
if (match[5]) {
rgb[3] = parseFloat(match[4]) * 0.01;
} else {
rgb[3] = parseFloat(match[4]);
}
}
} else if (match = string.match(keyword)) {
if (match[1] === 'transparent') {
return [0, 0, 0, 0];
}
if (!hasOwnProperty.call(colorNames, match[1])) {
return null;
}
rgb = colorNames[match[1]];
rgb[3] = 1;
return rgb;
} else {
return null;
}
for (i = 0; i < 3; i++) {
rgb[i] = clamp(rgb[i], 0, 255);
}
rgb[3] = clamp(rgb[3], 0, 1);
return rgb;
};
cs.get.hsl = function (string) {
if (!string) {
return null;
}
var hsl = /^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d\.]+)%\s*,?\s*([+-]?[\d\.]+)%\s*(?:[,|\/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/;
var match = string.match(hsl);
if (match) {
var alpha = parseFloat(match[4]);
var h = ((parseFloat(match[1]) % 360) + 360) % 360;
var s = clamp(parseFloat(match[2]), 0, 100);
var l = clamp(parseFloat(match[3]), 0, 100);
var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1);
return [h, s, l, a];
}
return null;
};
cs.get.hwb = function (string) {
if (!string) {
return null;
}
var hwb = /^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/;
var match = string.match(hwb);
if (match) {
var alpha = parseFloat(match[4]);
var h = ((parseFloat(match[1]) % 360) + 360) % 360;
var w = clamp(parseFloat(match[2]), 0, 100);
var b = clamp(parseFloat(match[3]), 0, 100);
var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1);
return [h, w, b, a];
}
return null;
};
cs.to.hex = function () {
var rgba = swizzle(arguments);
return (
'#' +
hexDouble(rgba[0]) +
hexDouble(rgba[1]) +
hexDouble(rgba[2]) +
(rgba[3] < 1
? (hexDouble(Math.round(rgba[3] * 255)))
: '')
);
};
cs.to.rgb = function () {
var rgba = swizzle(arguments);
return rgba.length < 4 || rgba[3] === 1
? 'rgb(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ')'
: 'rgba(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ', ' + rgba[3] + ')';
};
cs.to.rgb.percent = function () {
var rgba = swizzle(arguments);
var r = Math.round(rgba[0] / 255 * 100);
var g = Math.round(rgba[1] / 255 * 100);
var b = Math.round(rgba[2] / 255 * 100);
return rgba.length < 4 || rgba[3] === 1
? 'rgb(' + r + '%, ' + g + '%, ' + b + '%)'
: 'rgba(' + r + '%, ' + g + '%, ' + b + '%, ' + rgba[3] + ')';
};
cs.to.hsl = function () {
var hsla = swizzle(arguments);
return hsla.length < 4 || hsla[3] === 1
? 'hsl(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%)'
: 'hsla(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%, ' + hsla[3] + ')';
};
// hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
// (hwb have alpha optional & 1 is default value)
cs.to.hwb = function () {
var hwba = swizzle(arguments);
var a = '';
if (hwba.length >= 4 && hwba[3] !== 1) {
a = ', ' + hwba[3];
}
return 'hwb(' + hwba[0] + ', ' + hwba[1] + '%, ' + hwba[2] + '%' + a + ')';
};
cs.to.keyword = function (rgb) {
return reverseNames[rgb.slice(0, 3)];
};
// helpers
function clamp(num, min, max) {
return Math.min(Math.max(min, num), max);
}
function hexDouble(num) {
var str = Math.round(num).toString(16).toUpperCase();
return (str.length < 2) ? '0' + str : str;
}

state in react is returning back to the original value

I'am trying to implement a rogue like dungeon crawler game in react,I render the map before component mounts once and i later re-render the level using levelRender() function,but my state is returning back to its orginal value which is set by componentWillMount() function.Debugging shows that state is being chaged by levelRender() function but at end it returns to original state,which i think shouldn't be happening.I know my code is bit long but i guess problem lies with way i call componentWillMount() and levelRender() function.
In the game,brown box is the portal which should trigger the levelRender,when it is run over by player which is red box.
here is link to my codepen,use arrow keys to move around :)
const Map = React.createClass({
getInitialState() {
return {
width: 40,
height: 50,
wallRender: 0,
gameLevel: 0,
Probabilities: {
levelA: [3, 5, 2],
levelB: [3.5, 3, 3.5],
levelC: [8, 1, 1]
}
}
},
componentWillMount() {
document.addEventListener("keydown", this.handleKeyDown, false);
var map = [];
var rooms = [];
var render = [];
var level = this.state.gameLevel;
//use rot.js to generate map
var w = this.state.width,
h = this.state.height;
var objects = ["e", "h", "w"];
var probability;
var enemies = [];
var weapon = [];
var health = []
if (level == 0) {
probability = this.state.Probabilities.levelA;
} else if (level == 1) {
probability = this.state.Probabilities.levelB;
} else {
probability = this.state.Probabilities.levelC;
}
// var map = new ROT.Map.Digger();
var data = {};
var rotMap = new ROT.Map.Rogue(w, h);
var display = new ROT.Display({ width: w, height: h, fontSize: 6 });
rotMap.create(function (x, y, type) {
data[x + "," + y] = type;
display.DEBUG(x, y, type);
})
map = rotMap.map;
var rooms = rotMap.rooms;
// console.log(map);
// console.log(rooms)
var playerPosition = [rooms[0][0].x + 1, rooms[0][0].y + 1];
var portalPosition = [rooms[2][2].x + 2, rooms[2][2].y + 2];
// console.log(playerPosition)
map[playerPosition[0]][playerPosition[1]] = "p";
map[portalPosition[0]][portalPosition[1]] = "*";
var pp = playerPosition;
//
// set up enemies and health
rooms.map(function (rooms) {
rooms.map(function (room) {
var rx = room.x; var ry = room.y;
var noe = Math.floor(Math.random() * ((1 + 2) - 2 + 1)) + 2;
for (var i = 0; i < noe; i++) {
// generate enemy postions
var ex = Math.floor(Math.random() * ((room.width + rx) - rx + 1)) + rx;
var ey = Math.floor(Math.random() * ((room.height + ry) - ry + 1)) + ry;
if ((ex >= rx && ex < room.width + rx) && (ey >= ry && ey < room.height + ry)) {
var totalProbability = eval(probability.join("+"));//get total weight (in this case, 10)
var weighedObjects = new Array();//new array to hold "weighted" fruits
var currentObject = 0;
while (currentObject < objects.length) {
for (i = 0; i < probability[currentObject]; i++)
weighedObjects[weighedObjects.length] = objects[currentObject]
currentObject++
}
var randomnumber = Math.floor(Math.random() * totalProbability)
var x = weighedObjects[randomnumber];
if (x == 'e') {
map[ex][ey] = "e";
var stats = {
loc: ex + " " + ey,
health: 50,
damage: 20
}
enemies.push(stats)
} else if (x == 'h') {
map[ex][ey] = "h";
var stats = {
loc: ex + " " + ey,
boost: 80
}
health.push(stats)
} else if (x == 'w') {
map[ex][ey] = "w";
var stats = {
loc: ex + " " + ey,
damageBoost: 40
}
weapon.push(stats)
}
// console.log(ex + " " + ey + " " + (room.width + rx) + " " + (room.height + ry))
}
}
})
})
// place enemy
// console.log(enemies);
// console.log(health);
// console.log(weapon)
// setup field of view
var fov = this.setFov(pp)
this.setState({
gameState: map,
gameRooms: rooms,
playerPosition: playerPosition,
playerHealth: 50,
playerDamage: 5,
portalPosition: portalPosition,
fov: fov,
enemies: enemies,
health: health,
weapon: weapon
});
},
levelRender(){
console.log("level rendered")
var map = [];
var rooms = [];
var render = [];
var level=this.state.gameLevel;
//use rot.js to generate map
var w = this.state.width,
h = this.state.height;
var objects = ["e", "h", "w"];
var probability;
var enemies = [];
var weapon = [];
var health = []
if (level == 0) {
probability = this.state.Probabilities.levelA;
} else if (level == 1) {
probability = this.state.Probabilities.levelB;
} else {
probability = this.state.Probabilities.levelC;
}
// var map = new ROT.Map.Digger();
var data = {};
var rotMap = new ROT.Map.Rogue(w, h);
var display = new ROT.Display({ width: w, height: h, fontSize: 6 });
rotMap.create(function (x, y, type) {
data[x + "," + y] = type;
display.DEBUG(x, y, type);
})
map = rotMap.map;
var rooms = rotMap.rooms;
var playerPosition = [rooms[0][0].x + 1, rooms[0][0].y + 1];
if(level==0 || level ==1){
var portalPosition = [rooms[2][2].x + 2, rooms[2][2].y + 2];
map[portalPosition[0]][portalPosition[1]] = "*";
}else{
var bossPosition = [rooms[2][2].x + 2, rooms[2][2].y + 2];
map[portalPosition[0]][portalPosition[1]] = "boss";
}
map[playerPosition[0]][playerPosition[1]] = "p";
var pp = playerPosition;
//
// set up enemies and health
rooms.map(function (rooms) {
rooms.map(function (room) {
var rx = room.x; var ry = room.y;
var noe = Math.floor(Math.random() * ((1 + 2) - 2 + 1)) + 2;
for (var i = 0; i < noe; i++) {
// generate enemy postions
var ex = Math.floor(Math.random() * ((room.width + rx) - rx + 1)) + rx;
var ey = Math.floor(Math.random() * ((room.height + ry) - ry + 1)) + ry;
if ((ex >= rx && ex < room.width + rx) && (ey >= ry && ey < room.height + ry)) {
var totalProbability = eval(probability.join("+"));//get total weight (in this case, 10)
var weighedObjects = new Array();//new array to hold "weighted" fruits
var currentObject = 0;
while (currentObject < objects.length) {
for (i = 0; i < probability[currentObject]; i++)
weighedObjects[weighedObjects.length] = objects[currentObject]
currentObject++
}
var randomnumber = Math.floor(Math.random() * totalProbability)
var x = weighedObjects[randomnumber];
if (x == 'e') {
map[ex][ey] = "e";
var stats = {
loc: ex + " " + ey,
health: 50,
damage: 20
}
enemies.push(stats)
} else if (x == 'h') {
map[ex][ey] = "h";
var stats = {
loc: ex + " " + ey,
boost: 80
}
health.push(stats)
} else if (x == 'w') {
map[ex][ey] = "w";
var stats = {
loc: ex + " " + ey,
damageBoost: 40
}
weapon.push(stats)
}
// console.log(ex + " " + ey + " " + (room.width + rx) + " " + (room.height + ry))
}
}
})
})
// setup field of view
var fov = this.setFov(pp)
console.log(this.state.gameState)
this.setState({
gameState: map,
gameRooms: rooms,
playerPosition: playerPosition,
bossPosition:bossPosition,
portalPosition: portalPosition,
fov: fov,
enemies: enemies,
health: health,
weapon: weapon
});
console.log(this.state.gameState)
},
setFov(playerPos) {
var pp = playerPos;
var fov = [];
var x = pp[0]; var y = pp[1];
fov.push(x - 2 + "," + (y - 1)); fov.push(x - 2 + "," + y); fov.push(x - 2 + "," + (y + 1));
fov.push(x - 1 + "," + (y - 2)); fov.push(x - 1 + "," + (y - 1)); fov.push(x - 1 + "," + y); fov.push(x - 1 + "," + (y + 1)); fov.push(x - 1 + "," + (y + 2));
fov.push(x + "," + (y - 2)); fov.push(x + "," + (y - 1)); fov.push(x + "," + y); fov.push(x + "," + (y + 1)); fov.push(x + "," + (y + 2));
fov.push(x + 1 + "," + (y - 2)); fov.push(x + 1 + "," + (y - 1)); fov.push(x + 1 + "," + y); fov.push(x + 1 + "," + (y + 1)); fov.push(x + 1 + "," + (y + 2));
fov.push(x + 2 + "," + (y - 1)); fov.push(x + 2 + "," + y); fov.push(x + 2 + "," + (y + 1));
fov.push(x - 3 + "," + y); fov.push(x + 3 + "," + y); fov.push(x + "," + (y - 3)); fov.push(x + "," + (y + 3))
return fov;
},
handleKeyDown(e) {
// left arrow
var playerLoc = this.state.playerPosition;
if (e.keyCode == 37) {
var map = this.state.gameState;
var playerPos = this.state.playerPosition;
var x = playerPos[0], y = playerPos[1];
// console.log(map)
// console.log(playerPos)
if (map[(x)][(y - 1)] == 0 || map[(x)][(y - 1)] == "w" || map[(x)][(y - 1)] == "h" || map[(x)][(y - 1)] == "*") {
if (map[(x)][(y - 1)] == "*") {
var level = this.state.gameLevel + 1;
this.setState({
gameLevel:level
})
this.levelRender();
}
if (map[(x)][(y - 1)] == "h") {
var health = this.state.playerHealth + 30;
this.setState({
playerHealth: health
})
}
if (map[(x)][(y - 1)] == "w") {
var damage = this.state.playerDamage + 20;
this.setState({
playerDamage: damage
})
}
map[x][y] = 0;
map[(x)][(y - 1)] = "p";
playerPos[0] = x
playerPos[1] = y - 1;
}
// change fov
var pp = playerPos;
var fov = this.setFov(pp)
this.setState({
gameState: map,
playerPosition: playerPos,
fov: fov
})
}
// up arrow
if (e.keyCode == 38) {
var map = this.state.gameState;
var playerPos = this.state.playerPosition;
var x = playerPos[0], y = playerPos[1];
// console.log(map)
// console.log(playerPos)
if (map[(x - 1)][(y)] == 0 || map[(x - 1)][(y)] == "w" || map[(x - 1)][(y)] == "h") {
// update player health and damage
if (map[(x - 1)][(y)] == "h") {
var health = this.state.playerHealth + 30;
this.setState({
playerHealth: health
})
}
if (map[(x - 1)][(y)] == "w") {
var damage = this.state.playerDamage + 20;
this.setState({
playerDamage: damage
})
}
map[x][y] = 0;
map[(x - 1)][(y)] = "p";
playerPos[0] = x - 1
playerPos[1] = y;
}
// console.log(map)
// console.log(playerPos)
// change fov
var pp = playerPos;
var fov = this.setFov(pp)
this.setState({
gameState: map,
playerPosition: playerPos,
fov: fov
})
}
// right arrow
if (e.keyCode == 39) {
var map = this.state.gameState;
var playerPos = this.state.playerPosition;
var x = playerPos[0], y = playerPos[1];
// console.log(map)
// console.log(playerPos)
if (map[(x)][(y + 1)] == 0 || map[(x)][(y + 1)] == "w" || map[(x)][(y + 1)] == "h") {
// update player health and damage
if (map[(x)][(y + 1)] == "h") {
var health = this.state.playerHealth + 30;
this.setState({
playerHealth: health
})
}
if (map[(x)][(y + 1)] == "w") {
var damage = this.state.playerDamage + 20;
this.setState({
playerDamage: damage
})
}
map[x][y] = 0;
map[(x)][(y + 1)] = "p";
playerPos[0] = x
playerPos[1] = y + 1;;
}
//console.log(map)
//console.log(playerPos)
// change fov
var pp = playerPos;
var fov = this.setFov(pp)
this.setState({
gameState: map,
playerPosition: playerPos,
fov: fov
})
}
// down arrow
if (e.keyCode == 40) {
var map = this.state.gameState;
var playerPos = this.state.playerPosition;
var x = playerPos[0], y = playerPos[1];
if (map[(x + 1)][(y)] == 0 || map[(x + 1)][(y)] == "w" || map[(x + 1)][(y)] == "h") {
// update player health and damage
if (map[(x + 1)][(y)] == "h") {
var health = this.state.playerHealth + 30;
this.setState({
playerHealth: health
})
}
if (map[(x + 1)][(y)] == "w") {
var damage = this.state.playerDamage + 20;
this.setState({
playerDamage: damage
})
}
map[x][y] = 0;
map[(x + 1)][(y)] = "p";
playerPos[0] = x + 1
playerPos[1] = y;
}
// console.log(map)
// console.log(playerPos)
// change fov
var pp = playerPos;
var fov = this.setFov(pp)
this.setState({
gameState: map,
playerPosition: playerPos,
fov: fov
})
}
},
render() {
// rendering map
var map = this.state.gameState;
var fov = this.state.fov;
if(this.state.gameLevel==1){
console.log(map)
}
var render = [];
for (var i = 0; i < this.state.width; i++) {
var dummy = [];
for (var j = 0; j < this.state.height; j++) {
var arena = { background: "white", color: "white" };
var wallColor = "grey";
var wall = { background: wallColor, color: wallColor, border: "2px solid black" };
var enemy = { background: "blue", color: "blue" };
var player = { background: "red", color: "red" };
var health = { background: "green", color: "green" }
var weapon = { background: "orange", color: "orange" }
var portal = { background: "brown", color: "brown" }
var boss ={background:"yellow",color:"yellow"}
// check if cell is in fov
var val = i + "," + j;
if (map[i][j] == 0) {
// implement field of view
var x = arena;
// if (fov.includes(val)) {
// x.visibility = "visible";
// console.log(val)
// } else {
// x.visibility = "hidden";
// }
dummy.push(<td style={x}>00;</td>);
} else if (map[i][j] == "p") {
dummy.push(<td style={player}>00;</td>);
} else if (map[i][j] == "e") {
var x = enemy;
// if (fov.includes(val)) {
// x.visibility = "visible";
// } else {
// x.visibility = "hidden";
// }
dummy.push(<td border={5} style={enemy}>00;</td>);
} else if (map[i][j] == "h") {
var x = health;
// if (fov.includes(val)) {
// x.visibility = "visible";
// } else {
// x.visibility = "hidden";
// }
dummy.push(<td style={health}>00;</td>);
} else if (map[i][j] == "*") {
var x = portal;
// if (fov.includes(val)) {
// x.visibility = "visible";
// } else {
// x.visibility = "hidden";
// }
dummy.push(<td style={portal}>00;</td>);
}
else if (map[i][j] == "w") {
var x = weapon;
// if (fov.includes(val)) {
// x.visibility = "visible";
// } else {
// x.visibility = "hidden";
// }
dummy.push(<td style={weapon}>00;</td>);
}else if (map[i][j] == "boss") {
var x = boss;
// if (fov.includes(val)) {
// x.visibility = "visible";
// } else {
// x.visibility = "hidden";
// }
dummy.push(<td style={boss}>00;</td>);
}
else {
var x = wall;
// if (fov.includes(val)) {
// x.visibility = "visible";
// // console.log(val)
// } else {
// x.visibility = "hidden";
// }
// generate random hue of colors
dummy.push(<td style={wall}>00;</td>);
}
}
render.push(<tr>{dummy}</tr>);
}
return (
<div>
<div id="info">
<span id="health">Health:{this.state.playerHealth} </span>
<span id="damage">Damage:{this.state.playerDamage} </span>
<span id="message">{this.state.playerMessage}</span>
</div>
<div id="gameArea" tabIndex="0" >
<table align="right">
{render}
</table>
</div>
</div>
)
}
})
ReactDOM.render(<Map />, document.getElementById("app"));
You are setting the state in levelRender and overwriting the same with the previous state.
On line 452, this.leverRender is being invoked, which actually sets the new game state (desired). Later, on line 485, state is being overwritten with the variable map which has got the old values, which is responsible for the undesired output. This has to be resolved by setting the state only once, or setting it twice but with updated values of map.

Formatting Hijri and Gregorian Date

I get javascript codes for Hijri+Gregorian date. I want to put Hijri date first and next Gregorian like this:
Senin, 2 Januari 2017 M / 3 Rabiul Tsani 1438 H
to
Senin, 3 Rabiul Tsani 1438 H / 2 Januari 2017 M
Please help me, because i can't edit javascript codes.
This is the codes:
var fixd;
function isGregLeapYear(year) {
return year%4 == 0 && year%100 != 0 || year%400 == 0;
}
function gregToFixed(year, month, day) {
var a = Math.floor((year - 1) / 4);
var b = Math.floor((year - 1) / 100);
var c = Math.floor((year - 1) / 400);
var d = Math.floor((367 * month - 362) / 12);
if (month <= 2)
e = 0;
else if (month > 2 && isGregLeapYear(year))
e = -1;
else
e = -2;
return 1 - 1 + 365 * (year - 1) + a - b + c + d + e + day;
}
function Hijri(year, month, day) {
this.year = year;
this.month = month;
this.day = day;
this.toFixed = hijriToFixed;
this.toString = hijriToString;
}
function hijriToFixed() {
return this.day + Math.ceil(29.5 * (this.month - 1)) + (this.year - 1) * 354 + Math.floor((3 + 11 * this.year) / 30) + 227015 - 1;
}
function hijriToString() {
var months = new Array("Muharram","Safar","Rabiul Awwal","Rabiul Tsani","Jumadil Ula","Jumadil Tsani","Rajab","Sya\'ban","Ramadhan","Syawwal","Dzul Qa\'dah","Dzul Hijjah");
return this.day + " " + months[this.month -1]+ " " + this.year;
}
function fixedToHijri(f) {
var i=new Hijri(1100, 1, 1);
i.year = Math.floor((30 * (f - 227015) + 10646) / 10631);
var i2=new Hijri(i.year, 1, 1);
var m = Math.ceil((f - 29 - i2.toFixed()) / 29.5) + 1;
i.month = Math.min(m, 12);
i2.year = i.year;
i2.month = i.month;
i2.day = 1;
i.day = f - i2.toFixed() + 1;
return i;
}
var tod=new Date();
var weekday=new Array("Ahad","Senin","Selasa","Rabu","Kamis","Jumat","Sabtu");
var monthname=new Array("Januari","Februari","Maret","April","Mei"," Juni","Juli","Agustus","September","Oktober","November","Desember");
var y = tod.getFullYear();
var m = tod.getMonth();
var d = tod.getDate();
var dow = tod.getDay();
document.write(weekday[dow] + ", " + d + " " + monthname[m] + " " + y);
m++;
fixd=gregToFixed(y, m, d);
var h=new Hijri(1421, 11, 28);
h = fixedToHijri(fixd);
document.write(" M / " + h.toString() + " H ");
Finally, i can edit it by myself guys, hahaha, even I'm not programmer.
Thank you for your answer. If anyone wan to use this code, here, i'll share it.
function isGregLeapYear(year)
{
return year%4 == 0 && year%100 != 0 || year%400 == 0;
}
function gregToFixed(year, month, day)
{
var a = Math.floor((year -1) / 4);
var b = Math.floor((year - 1) / 100);
var c = Math.floor((year - 1) / 400);
var d = Math.floor((367 * month - 362) / 12);
if (month <= 2)
e = 0;
else if (month > 2&& isGregLeapYear(year))
e = -1;
else e = -2;
return 1 - 1 + 365 * (year - 1) + a - b + c + d + e + day;
}
function Hijri(year, month, day)
{
this.year = year;
this.month = month;
this.day = day;
this.toFixed = hijriToFixed;
this.toString = hijriToString;
}
function hijriToFixed()
{
return this.day +Math.ceil(29.5 * (this.month - 1)) +(this.year - 1) * 354 +
Math.floor((3 + 11* this.year) / 30) + 227015 - 1;
}
function hijriToString()
{
var months = new Array("Muharram","Safar","Rabiul Awal","Rabiul Akhir","Jumadil Awal","Jumadil Akhir","Rajab","Sya'ban","Ramadhan","Syawal","Zulqai'dah","Zulhijjah");
return this.day + " " +months[this.month -1]+ " " + this.year;
}
function fixedToHijri(f)
{
var i=new Hijri(1100, 1, 1);
i.year = Math.floor((30 * (f - 227015) + 10646) / 10631);
var i2=new Hijri(i.year, 1, 1);
var m = Math.ceil((f - 29- i2.toFixed()) / 29.5) + 1;
i.month = Math.min(m, 12);
i2.year = i.year;
i2.month = i.month;
i2.day = 1; i.day = f - i2.toFixed() + 1;
return i;
}
var tod=new Date();
var weekday=new Array ("Ahad","Senin","Selasa","Rabu","Kamis","Jumat","Sabtu");
var monthname=new Array("Januari","Februari","Maret","April","Mei"," Juni","Juli","Agustus","September","Oktober","November","Desember");
var y = tod.getFullYear();
var m = tod.getMonth();
var d = tod.getDate();
var dow = tod.getDay();
document.write(weekday[dow] + ", ");
m++;
fixd=gregToFixed(y, m, d);
var steve=new Hijri(1421, 11, 28);
steve = fixedToHijri(fixd);
document.write(" " + steve.toString() + " ");
document.write("/" + " " + d + " " + monthname[m] + " " + y);
m++;

Transform HH MM SS in seconds

I need to transform 3 form inputs (HH, MM, SS) in seconds with javascript.
I have this code but it has only with 1 form input in seconds : https://jsfiddle.net/94150148/hhomeLc3/
To do this I need a new javascript function.
window.onload = function () {generate()};
function generate() {
var width = 'width=\"' + document.getElementById('width').value + '\" ';
var height = 'height=\"' + document.getElementById('height').value + '\" ';
var ytid = "videoID";
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
if (start !== "") {
if(ytid === document.getElementById('ytid')) {
ytid += '?start=' + start;
}
else {
ytid += '&start=' + start;
}
}
if (end !== "") {
if (ytid === document.getElementById('ytid')) {
ytid += '?end=' + end;
}
else {
ytid += '&end=' + end;
}
}
document.getElementById('embedcode').value = '<iframe ' + width + height +
'src=\"https://www.youtube.com\/embed\/' + ytid +
'\" frameborder=\"0\"><\/iframe>';
}
function clearall() {
document.getElementById('width').value = 550;
document.getElementById('height').value = 315;
document.getElementById('start').value = "";
document.getElementById('end').value = "";
}
The jsFiddle to play with what I need : https://jsfiddle.net/94150148/ybmkcyyu/
https://jsfiddle.net/ybmkcyyu/3/
EDIT:
Do not display start and end when value is 0
https://jsfiddle.net/ybmkcyyu/6/
EDIT2:
https://jsfiddle.net/ybmkcyyu/7/
if (start !== "") {
ytid += '?start=' + start;
}
if (end !== "") {
if (start == "") {
ytid += '?end=' + end;
}
else {
ytid += '&end=' + end;
}
}
You just need to get value of every fields, as int, then add it with the formula: ((hours * 60) + minutes ) * 60 + secondes
And you might ensure that the result is a number. (if user enter a char instead of a number, it should not display something wrong)
var starth = parseInt(document.getElementById('starth').value);
var startm = parseInt(document.getElementById('startm').value);
var starts = parseInt(document.getElementById('starts').value);
var endh = parseInt(document.getElementById('endh').value);
var endm = parseInt(document.getElementById('endm').value);
var ends = parseInt(document.getElementById('ends').value);
var start = (((starth * 60) + startm) * 60) + starts;
if(isNaN(start) || start === 0)
start = "";
var end = (((endh * 60) + endm) * 60) + ends;
if(isNaN(end) || end === 0)
end = "";
/* (...) */
JS is generally quite good at math.
sHour = document.getElementById('starth').value,
sMin = document.getElementById('startm').value,
sSec = document.getElementById('starts').value,
sTime = (sHour * 3600) + (sMin * 60) + sSec;
https://jsfiddle.net/link2twenty/ybmkcyyu/4/

js (node.js) while loop not working

My node.js code is below.
Basically I have a buffer called searchRes and first I get some values from it.
It is supposed to loop round "results - 1" times.
It is looping.
It prints the first 3 bits of information totally correctly and then after that (4th onwards) is always the same as the 3rd one.
I have no idea why.
results = 20;
var sSize = searchRes.slice(8,16);
sSize = parseInt(sSize,16);
lols = new Array();
while(num <= results -1 ){
var cur = num + 1;
var sres=0;
for(var i in lols) { sres += lols[i]; }
if (num == 0){
var clanRes = searchRes.slice(0, 128 + (sSize * 2));
var cLen = clanRes.slice(8,16);
cLen = parseInt(cLen,16);
var firstLen = clanRes.length;
var lastLen = clanRes.length;
}else{
var cLen = searchRes.slice(lastLen + 8, lastLen + 16);
cLen = parseInt(cLen,16);
var clanRes = searchRes.slice(
lastLen,
lastLen + 128 + (cLen * 2)
);
var abc = 1;
if (abc == 1){
var lastLen = firstLen + clanRes.length;
abc++;
}else{
var lastLen = lastLen + clanRes.length;
}
}
lols.push(cLen);
console.log('\n\nClan ' + cur + ' Details');
var clanID = clanRes.slice(0,8);
clanID = parseInt(clanID,16);
num ++;
}
I'm not sure at all about where the problem is. Is it when defining clanRes or is it in making the loop?
Thanks!
**
Updated code for #bergi
**
num = 0;
var sSize = searchRes.slice(8,16);
sSize = parseInt(sSize,16);
lols = new Array();
while(num <= 3){
var cur = num + 1;
var sres=0;
for(var i in lols) { sres += lols[i]; }
if (num == 0){
var clanRes = searchRes.slice(0, 128 + (sSize * 2));
var cLen = clanRes.slice(8,16);
cLen = parseInt(cLen,16);
var firstLen = clanRes.length;
var lastLen = clanRes.length;
}else{
var cLen = searchRes.slice(lastLen + 8, lastLen + 16);
cLen = parseInt(cLen,16);
var clanRes = searchRes.slice(
lastLen,
lastLen + 128 + (cLen * 2)
);
var abc = 1;
if (abc == 1){
var lastLen = firstLen + clanRes.length;
abc++;
}else{
var lastLen = lastLen + clanRes.length;
}
}
lols.push(cLen);
console.log('\n\nClan ' + cur + ' Details');
var clanID = clanRes.slice(0,8);
clanID = parseInt(clanID,16);
console.log(clanID);
num ++;
}
Here is a exmaple searchRes:
http://pastie.org/10075399
And an example sSize:
0000000e - hex
14 - int.
var abc = 1;
if (abc == 1){
abc is always 1 in that comparison (the value is assigned right in the line before), so it will never evaluate the else block. I assume you want to move the initialisation of the variable out of the looping.

Categories