Add rows values of a time - javascript

I have set of three times in the format of Minute:Seconds:Miliseconds which I need to add to together and get the total time..
for example the one I have used is : 0:31.110 + 0:50.490 + 0:32.797
which = 1:54.397
so how to do this in javascript?
Here is JS Code
var sp1 = $('#table tr td:nth-child(2)').text()
var sp2 = $('#table tr td:nth-child(3)').text()
var sp3 = $('#table tr td:nth-child(4)').text()
var1 = sp1 + sp2 + sp3
$('td:nth-child(5)').html(var1);
I don't know where to begin but I have just come up with the above code..
I need the output to be 1:54.397 in the last td, but I get this 0:31.1100:50.4900:32.797 shown in this example http://jsfiddle.net/q1kumbea/

You may use moment.js for this. That would make it very easy, as you can just parse the times in the correct format, add the moments together ...
var sp1 = $('#table tr td:nth-child(2)').text()
var sp2 = $('#table tr td:nth-child(3)').text()
var sp3 = $('#table tr td:nth-child(4)').text()
var1 = moment(sp1, "mm:ss.SSS") + moment(sp2, "mm:ss.SSS") + moment(sp3, "mm:ss.SSS")
$('td:nth-child(5)').html(moment(var1).format("mm:ss.SSS"));
... and voila
Updated fiddle

I don't know any native functionality, but you can always(almost:) ) use some maths to achieve what you want. like below
var plusTimes = function(arr) {
var resultTime =0;
for(var i = 0; i < arr.length; i ++) {
resultTime += (parseInt((arr[i].split(':')[0]) * 60 * 1000) + ( parseInt(arr[i].split(':')[1].split('.')[0]) * 1000 ) + parseInt(arr[i].split('.')[1]))
}
var ms = (resultTime / 1000).toString().split('.')[1];
var sec = parseInt((resultTime / 1000).toString().split('.')[0]) % 60;
var min = (parseInt((114397 / 1000).toString().split('.')[0]) - parseInt((114397 / 1000).toString().split('.')[0]) % 60) / 60;
return min + ':' + sec + '.' + ms;
}
plusTimes(['0:31.110','0:50.490', '0:32.797']) // outputs "1:54.397"
you can add as many numbers as you wish to array unless you keep their format the same

Related

Code runs too slow

I'm trying to run a code that copies values from one spreadsheet and copies them to another, however the order is not the same(hard to make it an array). In some cases it also prints 'Unknown' and in some it also formats some cells. However it makes way to much time to finish. Is there a way to improve it?
function move() {
var sss = SpreadsheetApp.openById('xx');
var sourceSheet = sss.getSheetByName('CJ_Products');
var destinationSheet = sss.getSheetByName('Product2');
var lastRow = sourceSheet.getRange(sourceSheet.getLastRow(), 1,1,1).getRow()
var i = 1
while(i<=lastRow){
var rowInt = destinationSheet.getRange(destinationSheet.getLastRow()+1, 4,1,1).getRow() //get row number
destinationSheet.getRange('A' + rowInt).setFormula('=Month(D'+rowInt+')')
destinationSheet.getRange('B' + rowInt).setFormula('=Weekday(D'+rowInt+')')
destinationSheet.getRange('C' + rowInt).setFormula('=Day(D'+rowInt+')')
destinationSheet.getRange('D' + rowInt).setValue(sourceSheet.getRange('A'+i).getValues()) //move from the source to destination
destinationSheet.getRange('E' + rowInt+':F'+rowInt).setValue('Unknown') //set to Unknown
destinationSheet.getRange('H' + rowInt+':J'+rowInt).setValue('Unknown')
destinationSheet.getRange('J' + rowInt).setValue('CJ')
destinationSheet.getRange('K' + rowInt).setValue(sourceSheet.getRange('B' +i).getValues())
destinationSheet.getRange('L' + rowInt).setValue(sourceSheet.getRange('E' +i).getValues())
destinationSheet.getRange('M' + rowInt).setValue(sourceSheet.getRange('F' +i).getValues())
destinationSheet.getRange('N' + rowInt).setValue(sourceSheet.getRange('J' +i).getValues())
destinationSheet.getRange('S' + rowInt).setValue(sourceSheet.getRange('G' +i).getValues())
destinationSheet.getRange('T' + rowInt).setValue(sourceSheet.getRange('H' +i).getValues())
destinationSheet.getRange('O' + rowInt).setFormula('=S'+rowInt+'*GOOGLEFINANCE("currency:EURUSD")')
destinationSheet.getRange('P' + rowInt).setFormula('=T'+rowInt+'*GOOGLEFINANCE("currency:EURUSD")')
destinationSheet.getRange('Q' + rowInt).setFormula('=P'+rowInt+'/T'+rowInt)
destinationSheet.getRange('O' + rowInt+':Q'+rowInt).setNumberFormat('0.00$')
i = i+1
}
}
The code should be optimised:
You do all calculations in a loop
You use getValue and setValue instead of faster functions getValues, setValues
Instead of this concentrate your loop to do a single call:
var rowInt = destinationSheet.getRange(destinationSheet.getLastRow()+1, 4,1,1).getRow()
try to figure out how to find the first row outside the loop and then increment this value:
var rowStart = destinationSheet.getRange(destinationSheet.getLastRow()+1, 4,1,1).getRow();
for (var row = rowStart; row <= lastRow, row++)
{
// some code...
}
Use arrays and then copy the value from arrays into ranges:
var formulas = [];
for (var row = rowStart; row <= lastRow, row++)
{
// some code...
formulas.push(['=Month(D'+ row + ')']);
}
var rangeToPateFormulas = destinationSheet.getRange('A' + rowStart + ':A' + lastRow);
rangeToPateFormulas.setFormulas(formulas);
And so on. See more info:
https://developers.google.com/apps-script/reference/spreadsheet/range
https://developers.google.com/apps-script/guides/support/best-practices

Display two images every X hours, Javascript

Below is a code I am running to display a pair of images each day. I have been unable to have it display the images randomly, but instead each day it selects the next image in the Array (not at random). Javascript is not my specialty and I have been unsuccessful in making it select a new random image in both arrays each day.
I have also been unsuccessful in making it select them every 12 hours instead of each day, which is what I would prefer it to do. It must display the same ones for every person who views it for that period, until the timer resets, if possible.
<script type="text/javascript"><!--
var imlocation = "https://s31.postimg.org/";
function ImageArray (n) {
this.length = n;
for (var i =1; i <= n; i++) {
this[i] = ' '
}
}
function linkArray (n) {
this.length = n;
for (var i =1; i <= n; i++) {
this[i] = ' '
}
}
image = new ImageArray(4);
image[0] = 'v85buoebv/Day2.png';
image[1] = 'djdl322kr/Evening2.png';
image[2] = 'arubcg423/Night2.png';
image[3] = 'xf9kiljm3/Morning2.png';
link = new linkArray(11);
link[0] = 'q4xda5xdn/CLOUDY.png';
link[1] = '7141ttkjf/Heavyrain.png';
link[2] = 'gzp0gatyz/lightrain.png';
link[3] = 'xc3njrxob/Medium_Rain.png';
link[4] = 'x0m770h8b/NO_WEATHER.png';
link[5] = 's38mlwf97/omgrain.png';
link[6] = 'btigj04l7/Special_Weather.png';
link[7] = 'b59m025vf/WEREALLGONNADIErain.png';
link[8] = 'ubmt38md7/Windy.png';
link[9] = 'x0m770h8b/NO_WEATHER.png';
link[10] = 'x0m770h8b/NO_WEATHER.png';
var currentdate = new Date();
var imagenumber = currentdate.getDay();
document.write('<div id="NOTICEME"><center><img src="' + imlocation + image[imagenumber] + '"><img src="' + imlocation + link[imagenumber] + '"></center><br><div id="mowords">[center][img]' + imlocation + image[imagenumber] + '[/img][img]' + imlocation + link[imagenumber] + '[/img][/center]</div></div>');
//--></script>
I used this code as a base to go on. But no matter how I toy with it, it won't give me a random image from the array. Also, the div ID "mowords" and "NOTICEME" is an ID I am using for CSS reasons that has nothing to do with this code.
Edit:
Maybe going for random is the wrong way to do this. Is there a way to make the link = new linkArray select the date (as in 1 - 31) and the image = new ImageArray select the day (as in 1 - 7) like it is currently doing? It will create variance and the illusion of randomness in the long run.
If you know your arrays' indices, and they are integers, then you can use the following to get a pseudo-random integer between min and max:
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
Now, however, your approach has been giving you certain "consistency" in your results, i.e. each day of the week giving you a certain image on every page show.
If you wish to implement randomness into it, you won't get such consistent results, meaning that on every page show, the image will be random independent of the day of the week or time of day.
To address this issue, you can take several approaches:
Have a server-side scripting language define the images (random or not) and save the "daily"/12-hour preferences into a .json/.js file, which then can be read by the JavaScript running in the browser. With this approach you would probably set the "refresh" rate via adding Expires headers on the .js file handling the parsing of the configuration file created by your server-side script -> https://gtmetrix.com/add-expires-headers.html
The other approach is to redefine your image selection logic based on the current date/time. However, the obvious downfall to that, is that you rely on the date and time of the user's computer, which can't always be trusted, so you have to work around that.
I would advise to look into a server-side scripting solution - PHP/Perl would do fine for this purpose.
UPDATED:
Have not tested, but try this (as per your comments):
<script type="text/javascript"><!--
var imlocation = "https://s31.postimg.org/";
function ImageArray (n) {
this.length = n;
for (var i = 0; i <= n; i++) {
this[i] = ''
}
}
function linkArray (n) {
this.length = n;
for (var i = 0; i <= n; i++) {
this[i] = ''
}
}
image = new ImageArray(6);
image[0] = 'v85buoebv/Day2.png';
image[1] = 'djdl322kr/Evening2.png';
image[2] = 'arubcg423/Night2.png';
image[3] = 'xf9kiljm3/Morning2.png';
image[4] = '';
image[5] = '';
image[6] = '';
link = new linkArray(30);
link[0] = 'q4xda5xdn/CLOUDY.png';
link[1] = '7141ttkjf/Heavyrain.png';
link[2] = 'gzp0gatyz/lightrain.png';
link[3] = 'xc3njrxob/Medium_Rain.png';
link[4] = 'x0m770h8b/NO_WEATHER.png';
link[5] = 's38mlwf97/omgrain.png';
link[6] = 'btigj04l7/Special_Weather.png';
link[7] = 'b59m025vf/WEREALLGONNADIErain.png';
link[8] = 'ubmt38md7/Windy.png';
link[9] = 'x0m770h8b/NO_WEATHER.png';
link[10] = 'x0m770h8b/NO_WEATHER.png';
link[11] = '';
link[12] = '';
link[13] = '';
link[14] = '';
link[15] = '';
link[16] = '';
link[17] = '';
link[18] = '';
link[19] = '';
link[20] = '';
link[21] = '';
link[22] = '';
link[23] = '';
link[24] = '';
link[25] = '';
link[26] = '';
link[27] = '';
link[28] = '';
link[29] = '';
link[30] = '';
var currentdate = new Date();
var dM = currentdate.getDate() - 1;
var dW = currentdate.getDay();
//var imagenumber = currentdate.getDay();
document.write('<div id="NOTICEME"><center><img src="' + imlocation + image[dW] + '"><img src="' + imlocation + link[dM] + '"></center><br><div id="mowords">[center][img]' + imlocation + image[dW] + '[/img][img]' + imlocation + link[dM] + '[/img][/center]</div></div>');
//--></script>
You use the function getDay() on the currentDate, therefore it will not change throughout a single day. Have a look at http://www.w3schools.com/jsref/jsref_getday.asp where you notice that its an integer from 0 to 6, and the week starts on sunday.
Therefore today (wednesday august 03 is 3) you should see image[3] and link[3]. Tomorrow you should get an error because you will reference outside of the image array i.e. image[4] will throw an index out of bounds exception.
Well, here goes my first answer here ever!
JavaScript is client-side code, so if the JavaScript code is what is determining the random number (rather than server-side code), you can't guarantee everyone accessing the site sees the same thing.
You could, however, use the date and time as a seed to generate what could appear random:
var btn = document.getElementById('btn');
btn.onclick = function () {
var d = new Date();
// getHours() results in an integer 0-23
var h = d.getUTCHours();
var chooser;
//Pick a multiplier based on the time of day.
if (h < 12) {
chooser = 1.15;
} else {
chooser = 1.87;
}
//Change upperLimit to whatever the upper limit of your array may end up being.
var upperLimit = 10;
//Generate the result
var pseudoRand = parseInt((d.getUTCFullYear() + d.getUTCMonth() + d.getUTCDay()) * chooser % upperLimit);
btn.textContent = pseudoRand;
}
Fiddle: https://jsfiddle.net/tapjzg94/
That code replaces the text of the button with an integer from 0 to upperLimit that should be the same for everyone who clicks on it, avoiding time zone issues with the UTC versions of the Date functions.
You could mix and match the date functions however you want, so long as they are all numbers that don't change on a rapid basis (year/month/date/day vs. minutes/seconds/milliseconds).

Fabric.js Images in a pyramid

I have some very wet code with coordinates for to make a pyramid with a wide base, out of images in frabric.js
I have tried all day to succeed in writing a loop to dry up the code. I'm somewhat of a beginner, so I cannot get it into my head how to do this.
Please can someone help. I've looked around and found how to do something similar with circles in fabric.js, but I can't seem to translate it into images.
The loop also needs to increment a row number, so fabric knows when to add the next row.
This is the terrible code I have.
var canvasWidth = 1000;
var imageWidth = 20;
var row1 = 1;
var a = canvasWidth/2-(imageWidth)*1/2+imageWidth*0;
var row2 = 11;
var b = canvasWidth/2-(imageWidth)*2/2+imageWidth*0;
var c = canvasWidth/2-(imageWidth)*2/2+imageWidth*1;
var row3 = 21
var d = canvasWidth/2-(imageWidth)*3/2+imageWidth*0;
var e = canvasWidth/2-(imageWidth)*3/2+imageWidth*1;
var f = canvasWidth/2-(imageWidth)*3/2+imageWidth*2;
var row4 = 31
var g = canvasWidth/2-(imageWidth)*4/2+imageWidth*0;
var h = canvasWidth/2-(imageWidth)*4/2+imageWidth*1;
var i = canvasWidth/2-(imageWidth)*4/2+imageWidth*2;
var j = canvasWidth/2-(imageWidth)*4/2+imageWidth*3;
var row5 = 41
var k = canvasWidth/2-(imageWidth)*5/2+imageWidth*0;
var m = canvasWidth/2-(imageWidth)*5/2+imageWidth*1;
var n = canvasWidth/2-(imageWidth)*5/2+imageWidth*2;
var o = canvasWidth/2-(imageWidth)*5/2+imageWidth*3;
var p = canvasWidth/2-(imageWidth)*5/2+imageWidth*4;
console.log("Row1: "+a +
" Row2: "+ b + "," + c+
" Row3: "+ d + "," + e+ ","+ f +
" Row4: "+ g + "," + h +","+ i + "," + j +
" Row5: "+ k + "," + m +","+ n + "," + o + "," + p);
To make correct loop you should understand what you Iterate, here, you are iterating rows and cells (bricks may be correct name), so to make a loop you should just make loop in loop, like in table:
var canvasWidth = 1000;
var imageWidth = 20;
var rows = [];
for (var row = 1; row <= 5; row++) { // use let in es6
var cells = []; // use let in es6
rows[row - 1] = cells;
for (var cell = 0; cell <= row - 1; cell++) { // use let in es6
cells[cell] = canvasWidth / 2 - (imageWidth) * row / 2 + imageWidth * cell;
}
}
console.log(rows);

Are classes indexed in modern browsers?

In past web development I have always tried to descend from an id when constructing a selector in javascript, previously in jQuery and more recently using document.querySelector()/.querySelectorAll(). This was for performance reasons. I was following advice in posts like this (http://www.artzstudio.com/2009/04/jquery-performance-rules/#descend-from-id).
For example:
$('#new-address-form input.address')
could be significantly faster than
$('.address')
Even when there was only one element on the page with a class of address. If there were a lot of different classes in the DOM, this could be a lot faster in some browsers (I'm looking at you IE<8).
But, experientially, it seems today that this is no longer the case. Can anyone point me to some documentation or code, for open-source browsers, that would confirm that modern browsers index elements by class?
The difference in performance is there, but it may not be significant unless you're working with a very large markup.
I setup a benchmark JS Fiddle that creates 20,000 div tags each nested 10 levels deep. Then attempts to select one at random based on class, and again based on ID with a descendant class.
I've benchmarked it here: https://jsfiddle.net/0wyLfnz8/14/
Results
Selecting by ID then descendant class was on average .018ms in Chrome
Selecting by ID then descendant class was on average 39.33ms in IE
Selecting by class alone was on average 12.178ms in Chrome
Selecting by class alone was on average 51.386ms in IE
Again, those results are in milliseconds with 500 tests over 20,000 HTML elements
Code for Benchmarking
$(document).ready(function() {
var d = new Date();
var st = d.getTime();
var start = st;
var et;
var max = 20000;
var numberOfTests = 500;
var elementDepth = 10;
for(var i = 1; i < max; i++) {
//lets make a random class too
r = Math.floor((Math.random() * 10) + 1);
var depth = "";
for(var j = 1; j<elementDepth;j++) {
depth += '<div class="depth' + j + '"></div>'
}
$('body').append('<div id="d'+i+'">'+depth+'<div class="depth'+elementDepth+'"><div class="c'+i+' r'+r+'">Hello, I am div number '+i+'</div></div></div>');
}
d = new Date();
var duration = d.getTime() - st;
console.log('Generating divs took ' + (duration/1000) + ' seconds');
idDuration = 0;
idTests = 0;
for(var i = 0; i < numberOfTests; i++) {
//choose a random div to select
r = Math.floor((Math.random() * max) + 1);
d = new Date();
st = d.getTime();
var tagbyID = $('#d'+r+ '.c'+r);
d = new Date();
et = d.getTime();
duration = et - st;
//console.log('Selecting by ID took ' + duration + ' milliseconds');
idDuration += duration;
idTests++;
}
console.log('---');
classDuration = 0;
classTests = 0;
for(var i = 0; i < numberOfTests; i++) {
//choose a random div to select
r = Math.floor((Math.random() * max) + 1);
d = new Date();
st = d.getTime();
var tagbyClass = $('.c'+r);
d = new Date();
et = et;
duration = d.getTime() - st;
//console.log('Selecting by class took ' + duration + ' milliseconds');
classDuration += duration;
classTests++;
}
console.log('---');
d = new Date();
console.log('total duration: ' + ((d.getTime() - start)/1000) + " seconds");
console.log('---');
console.log('Selecting by ID took '+idDuration+' milliseconds total over '+idTests+' tests.');
console.log('Selecting by class took '+classDuration+' milliseconds total over '+classTests+' tests.');
console.log('---');
console.log('Average time for ID selection using $(\'#parentID .childClassName\') was: ' + (idDuration / idTests)+" milliseconds")
console.log('Average time for class selection using $(\'.className\') was: ' + (classDuration / classTests)+" milliseconds")
})
I may have answered my own question. I created a jsperf, but I would value more test data or improvements.
http://jsperf.com/should-we-always-descend-by-an-id/6
EDIT: In my test case it looks like jQuery is actually faster when you DON'T descend from an id, but the clear performance winner (cross-browser) is document.getElementsByClassName().

Multiple Rows and Columns in Jquery

I have a jquery code that displays results in one row and multiple columns as follows
function () {
var i = noDays;
var days = 30;
while (i < days) {
$('tr').append('<td> ' + i + ' </td>');
i++;
},
}
When I have more than 10 results (10 columns), the row stretch outside the page
How can I divide the row into multiple rows for instance?
if I have 30 columns in 1 row
I would like to instead have 6 columns and 5 rows
Not sure exactly where you're appending the data, but look at the code here: http://jsfiddle.net/kdst5/1/ - using the modulus operator on "i" can tell you when you to move to a new line; Additionally, instead of using $("tr"), you should use a specific selector, not necessarily the variable that I used, but something more specific than a general "every TR" selector.
It is better to create an element and use a reference to it, as opposed to having jquery fire off a selector in every pass.
Here is a working solution and its jsfiddle:
var $table = $("#myTable");
var i = 1;
var days = 30;
var $tr = $("<tr>");
while (i <= days) {
$tr.append('<td>' + i++ + '</td>');
if (i %6 == 1) {
$table.append($tr);
$tr = $("<tr>");
}
};
$("#myTable").append($tr);

Categories

Resources