javascript multiple AND conditions in IF statement inside for loop javascript - javascript

I feel stupid because I´m stuck with a basic. I have three set of classes that contains paragraphs and I want to change the background color of each one depending on day (with New Dat.getDay().
I dont know how to mix for loop and if statements for each set of classes correctly. I guess it´s something simple but I missing it!
function changecolor() {
var d = new Date();
var n = d.getDay();
var weekda = document.getElementsByClassName('weekdays');
var sat = document.getElementsByClassName('saturday');
var dom = document.getElementsByClassName('sun-fer');
for (var i = 0; i < weekda.length && i < sat.length && i < dom.length; i++)
if (n > 0 || n < 6) {
weekda[i].setAttribute("style", "background-color:#0091ea;color:white;");
}
else if (n == 6) {
sat[i].setAttribute("style", "background-color:#0091ea;color:white;");
} else {
dom[i].setAttribute("style", "background-color:#0091ea;color:white;");
}
}
}
changecolor();

You need to group conditions. Read more about Operator precedence
for (var i = 0;( (i < weekda.length) && (i < sat.length) && (i < dom.length)); i++){
// your code
}

Part of the problem may be you have background-color:#0091ea;color:white; for all three options. Therefore you may not be seeing any change.
Personally I would break this up a little to make it more flexible and a little easier to read (and maintain). For example:
function changecolor() {
var d = new Date();
var e = null;
var s = null;
switch(d.getDay()) {
case 6:
e = document.getElementsByClassName('saturday');
s = "background-color:#0091ea;color:white;";
break;
case 0:
e = document.getElementsByClassName('sun-fer');
s = "background-color:#0091ea;color:green;";
break;
default:
e = document.getElementsByClassName('weekdays');
s = "background-color:#0091ea;color:blue;";
}
// now update the color
updateItem(e,s);
}
function updateItem(e,s) {
var i, max = e.length;
for(i=0;i<max;i++) {
e[i].setAttribute("style",s);
}
}

Related

App version compare with different version format

Need some help regarding a small bit of code which needs some expert advice. It is a code I wrote on my own for comparing versions of an application with that of app store version. It has some small flaw but I couldn't move forward with it. Any help will be greatly valuable.
function versionCompare(appVersionInStore, appVersionInReq) {
var versionStoreArray = appVersionInStore.split('.');
var versionReqArray = appVersionInReq.split('.');
var arrIndex;
var len = Math.max(versionStoreArray.length, versionReqArray.length);
for (var i = 0; i < versionStoreArray.length; i++) {
if (versionStoreArray[i].length < 2) {
versionStoreArray[i] = '0' + versionStoreArray[i];
}
}
for (var i = 0; i < versionReqArray.length; i++) {
if (versionReqArray[i].length < 2) {
versionReqArray[i] = '0' + versionReqArray[i];
}
}
appVersionInStore = versionStoreArray.join('');
appVersionInReq = versionReqArray.join('');
appVersionInStore = parseInt(appVersionInStore);
appVersionInReq = parseInt(appVersionInReq);
var result = appVersionInStore - appVersionInReq;
return result;
}
var versionDifference = versionCompare('3.1.2', '3.1.7');
if (versionDifference >= 4) {
appUpdatePolicy = 'MANDATORY';
} else if ((versionDifference >= 1) && (versionDifference <= 3)) {
appUpdatePolicy = 'OPTIONAL';
} else if ((versionDifference <= 0)) {
appUpdatePolicy = 'NONE';
}
return appUpdatePolicy;
This is returning appUpdatePolicy with three values - MNADATORY, OPTIONAL, OR NONE based on the versionCompare() function. Now if the version are in similar format(3.1.1 - 2 decimal or 17.2 - 1 decimal) and are being compared, its working fine. If they are not in similar format (3.1.2 being compared with 17.2), it's not working fine. Any helps on this?
We have a use case where in the version can be in different format possibly.

indexOf() : is there a better way to implement this?

EDIT
Thank you guys, and i apologize for not being more specific in my question.
This code was written to check if a characters in the second string is in the first string. If so, it'll return true, otherwise a false.
So my code works, I know that much, but I am positive there's gotta be a better way to implement this.
Keep in mind this is a coding challenge from Freecodecamp's Javascript tree.
Here's my code:
function mutation(arr) {
var stringOne = arr[0].toLowerCase();
var stringTwo = arr[1].toLowerCase().split("");
var i = 0;
var truthyFalsy = true;
while (i < arr[1].length && truthyFalsy) {
truthyFalsy = stringOne.indexOf(stringTwo[i]) > -1;
i++
}
console.log(truthyFalsy);
}
mutation(["hello", "hey"]);
//mutation(["hello", "yep"]);
THere's gotta be a better way to do this. I recently learned about the map function, but not sure how to use that to implement this, and also just recently learned of an Array.prototype.every() function, which I am going to read tonight.
Suggestions? Thoughts?
the question is very vague. however what i understood from the code is that you need to check for string match between two strings.
Since you know its two strings, i'd just pass them as two parameters. additionally i'd change the while into a for statement and add a break/continue to avoid using variable get and set.
Notice that in the worst case its almost the same, but in the best case its half computation time.
mutation bestCase 14.84499999999997
mutation worstCase 7.694999999999993
bestCase: 5.595000000000027
worstCase: 7.199999999999989
// your function (to check performance difference)
function mutation(arr) {
var stringOne = arr[0].toLowerCase();
var stringTwo = arr[1].toLowerCase().split("");
var i = 0;
var truthyFalsy = true;
while (i < arr[1].length && truthyFalsy) {
truthyFalsy = stringOne.indexOf(stringTwo[i]) > -1;
i++
}
return truthyFalsy;
}
function hasMatch(base, check) {
var strOne = base.toLowerCase();
var strTwo = check.toLowerCase().split("");
var truthyFalsy = false;
// define both variables (i and l) before the loop condition in order to avoid getting the length property of the string multiple times.
for (var i = 0, l = strTwo.length; i < l; i++) {
var hasChar = strOne.indexOf(strTwo[i]) > -1;
if (hasChar) {
//if has Char, set true and break;
truthyFalsy = true;
break;
}
}
return truthyFalsy;
}
var baseCase = "hello";
var bestCaseStr = "hey";
var worstCaseStr = "yap";
//bestCase find match in first iteration
var bestCase = hasMatch("hello", bestCaseStr);
console.log(bestCase);
//worstCase loop over all of them.
var worstCase = hasMatch("hello", worstCaseStr);
console.log(worstCase);
// on your function
console.log('mutation bestCase', checkPerf(mutation, [baseCase, bestCaseStr]));
console.log('mutation worstCase', checkPerf(mutation, [baseCase, worstCaseStr]));
// simple performance check
console.log('bestCase:', checkPerf(hasMatch, baseCase, bestCaseStr));
console.log('worstCase:', checkPerf(hasMatch, baseCase, worstCaseStr));
function checkPerf(fn) {
var t1 = performance.now();
for (var i = 0; i < 10000; i++) {
fn(arguments[1], arguments[2]);
}
var t2 = performance.now();
return t2 - t1;
}

"Look and say sequence" in javascript

1
11
12
1121
122111
112213
122211
....
I was trying to solve this problem. It goes like this.
I need to check the former line and write: the number and how many time it was repeated.
ex. 1 -> 1(number)1(time)
var antsArr = [[1]];
var n = 10;
for (var row = 1; row < n; row++) {
var lastCheckedNumber = 0;
var count = 1;
antsArr[row] = [];
for (var col = 0; col < antsArr[row-1].length; col++) {
if (lastCheckedNumber == 0) {
lastCheckedNumber = 1;
antsArr[row].push(lastCheckedNumber);
} else {
if (antsArr[row-1][col] == lastCheckedNumber) {
count++;
} else {
lastCheckedNumber = antsArr[row-1][col];
}
}
}
antsArr[row].push(count);
antsArr[row].push(lastCheckedNumber);
}
for (var i = 0; i < antsArr.length; i++) {
console.log(antsArr[i]);
}
I have been on this since 2 days ago.
It it so hard to solve by myself. I know it is really basic code to you guys.
But still if someone who has a really warm heart help me out, I will be so happy! :>
Try this:
JSFiddle Sample
function lookAndSay(seq){
var prev = seq[0];
var freq = 0;
var output = [];
seq.forEach(function(s){
if (s==prev){
freq++;
}
else{
output.push(prev);
output.push(freq);
prev = s;
freq = 1;
}
});
output.push(prev);
output.push(freq);
console.log(output);
return output;
}
// Sample: try on the first 11 sequences
var seq = [1];
for (var n=0; n<11; n++){
seq = lookAndSay(seq);
}
Quick explanation
The input sequence is a simple array containing all numbers in the sequence. The function iterates through the element in the sequence, count the frequency of the current occurring number. When it encounters a new number, it pushes the previously occurring number along with the frequency to the output.
Keep the iteration goes until it reaches the end, make sure the last occurring number and the frequency are added to the output and that's it.
I am not sure if this is right,as i didnt know about this sequence before.Please check and let me know if it works.
var hh=0;
function ls(j,j1)
{
var l1=j.length;
var fer=j.split('');
var str='';
var counter=1;
for(var t=0;t<fer.length;t++)
{
if(fer[t]==fer[t+1])
{
counter++;
}
else
{
str=str+""+""+fer[t]+counter;
counter=1;
}
}
console.log(str);
while(hh<5) //REPLACE THE NUMBER HERE TO CHANGE NUMBER OF COUNTS!
{
hh++;
//console.log(hh);
ls(str);
}
}
ls("1");
You can check out the working solution for in this fiddle here
You can solve this by splitting your logic into different modules.
So primarily you have 2 tasks -
For a give sequence of numbers(say [1,1,2]), you need to find the frequency distribution - something like - [1,2,2,1] which is the main logic.
Keep generating new distribution lists until a given number(say n).
So split them into 2 different functions and test them independently.
For task 1, code would look something like this -
/*
This takes an input [1,1,2] and return is freq - [1,2,2,1]
*/
function find_num_freq(arr){
var freq_list = [];
var val = arr[0];
var freq = 1;
for(i=1; i<arr.length; i++){
var curr_val = arr[i];
if(curr_val === val){
freq += 1;
}else{
//Add the values to the freq_list
freq_list.push([val, freq]);
val = curr_val;
freq = 1;
}
}
freq_list.push([val, freq]);
return freq_list;
}
For task 2, it keeps calling the above function for each line of results.
It's code would look something like this -
function look_n_say(n){
//Starting number
var seed = 1;
var antsArr = [[seed]];
for(var i = 0; i < n; i++){
var content = antsArr[i];
var freq_list = find_num_freq(content);
//freq_list give an array of [[ele, freq],[ele,freq]...]
//Flatten so that it's of the form - [ele,freq,ele,freq]
var freq_list_flat = flatten_list(freq_list);
antsArr.push(freq_list_flat);
}
return antsArr;
}
/**
This is used for flattening a list.
Eg - [[1],[1,1],[1,2]] => [1,1,1,1,2]
basically removes only first level nesting
**/
function flatten_list(li){
var flat_li = [];
li.forEach(
function(val){
for(ind in val){
flat_li.push(val[ind]);
}
}
);
return flat_li;
}
The output of this for the first 10 n values -
OUTPUT
n = 1:
[[1],[1,1]]
n = 2:
[[1],[1,1],[1,2]]
n = 3:
[[1],[1,1],[1,2],[1,1,2,1]]
n = 4:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1]]
n = 5:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3]]
n = 6:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3],[1,2,2,2,1,1,3,1]]
n = 7:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3],[1,2,2,2,1,1,3,1],[1,1,2,3,1,2,3,1,1,1]]
n = 8:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3],[1,2,2,2,1,1,3,1],[1,1,2,3,1,2,3,1,1,1],[1,2,2,1,3,1,1,1,2,1,3,1,1,3]]
n = 9:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3],[1,2,2,2,1,1,3,1],[1,1,2,3,1,2,3,1,1,1],[1,2,2,1,3,1,1,1,2,1,3,1,1,3],[1,1,2,2,1,1,3,1,1,3,2,1,1,1,3,1,1,2,3,1]]

How to cycle between two arrays

I'm trying to create a cycling sliding animation for set of elements, i have two arrays:
var elms = [elm1, elm2, elm3];
var props = [{x,y,width,height,z-index,opacite,....}, {....}, {....}];
on initializing, elms will be positioned in the same order as props: "-> is not part of the syntax it's just to make things easier to explain and it means 'do something with'"
elms[0] -> props[0];
emls[1] -> props[1];
elms[2] -> props[2];
but then i want to cycle them like:
elms[0] -> props[2]
elms[1] -> props[0]
elms[2] -> props[1]
and then:
elms[0] -> props[1]
elms[1] -> props[2]
elms[2] -> props[0]
and so forth...
i tried this:
function index(n, array){
var m = n;
if(n > array.length){
m = n - array.lenth;
}else if(n < 0){
m = array.length + n;
}
return m;
}
var active = 0; //the front element
function slide(direction){
for (i=0; i< elms.length; i++)
{
elms[i] -> props[index(i - active, props)]
}
if(direction == 'fw'){
if(active++ => elms.length){
active = 0;
}else{
active++;
}
}else if(direction == 'bw'){
if(active-- < 0){
active += elms.length;
}else{
active--;
}
}
}
setInterval(function(){slide('fw')}, 3000);
now the above code works fine, but i'm sure this has been done many times before and i'm wondering does anyone know if there is a better less complicated way to do this which allows to loop forward and backward?
If you don't mind modifying the props array, you can just .shift() off the first element and then .push() is onto the end of the array and then once again do:
elms[0] -> props[0];
emls[1] -> props[1];
elms[2] -> props[2];
To rotate the props array, you could just do this:
function rotateProps() {
var front = props.shift();
props.push(front);
}
So, each cycle just call rotateProps() and then repeat what you did the first time.
How about using module? Have a global var that you increment each time you shift, then module that with the length of the arrays. You could access the arrays like: props[shift%len]
If len is 3 (as above), you could get these results if you are accessing the props in relation to the first elmsIdx (0):
POC: jsfiddle.net/Q8dBb, also this would work without modifying your arrays so I believe it would be faster
shift = 0; // (shift+elmsIdx)%len == 0;
shift = 1; // (shift+elmsIdx)%len == 1;
shift = 2; // (shift+elmsIdx)%len == 2;
shift = 3; // (shift+elmsIdx)%len == 0;
shift = 4; // (shift+elmsIdx)%len == 1;
etc
Actually, using an object could make it more flexible (shifting multiple ways, resetting, whatever you want to add). Here is an example for that:
function Shift(len) {
var _len = len;
var _s = 0;
this.left = function() {
_s = (_s + 1)% _len;
}
this.right = function() {
_s = (_s - 1);
if (_s < 0) {
_s = _s + _len;
}
}
this.get = function(idx) {
return (_s + idx)% _len;
}
this.reset = function() {
_s = 0;
}
}
in use: http://jsfiddle.net/6tSup/1/

Text area transposition

I am a beginner and I've found some useful examples for what I want to do. The problem is the examples that I've found don't have enough comments for me to understand what is going on. So, I hope someone can help me implement the code I've found into the code that I already have. I'm making a text manipulation area to use to play with cipher text. It's all being done inside a single HTML text area. I've got a functions called, "function G_Group(size, count)", that breaks the text into rows and columns of choice and it is working great. The next tool that I want to add will transpose this matrix from (x,y) to (y,x). Because I have the "function G-Group" function, I don't believe I need to slice anything. I found a bit of JavaScript transposition code at http://rosettacode.org/wiki/Matrix_transposition#JavaScript but I don't know how to change the values to add it to what I've got already.
Function G_Group(size, count) is called like this.
<input type= button value="Grouping" onclick = "return G_Group(0, 0)" title="grouping" />
And here is the how i break text up into rows and columns:
function G_Group(size, count)
{
if (size <= 0)
{
size = document.encoder.group_size.value;
if (size <= 0)
{
alert('Invalid group size');
return false;
}
}
if (count <= 0)
{
count = document.encoder.group_count.value;
if (count <= 0)
{
alert('Invalid group count');
return false;
}
}
var t = document.encoder.text.value;
var o = '', groups = 0;
t = Tr(t, " \r\n\t");
while (t.length > 0)
{
if (o.length > 0)
{
o += ' ';
}
if (groups >= count)
{
o += "\n";
groups = 0;
}
groups ++;
o += t.slice(0, size);
t = t.slice(size, t.length);
}
document.encoder.text.value = o;
return false;
}
And this is the code that I want modify to transpose the array.
function Matrix(ary) {
this.mtx = ary
this.height = ary.length;
this.width = ary[0].length;
}
Matrix.prototype.toString = function() {
var s = []
for (var i = 0; i < this.mtx.length; i++)
s.push( this.mtx[i].join(",") );
return s.join("\n");
}
// returns a new matrix
Matrix.prototype.transpose = function() {
var transposed = [];
for (var i = 0; i < this.width; i++) {
transposed[i] = [];
for (var j = 0; j < this.height; j++) {
transposed[i][j] = this.mtx[j][i];
}
}
return new Matrix(transposed);
}
I am aware that I may be approaching this all wrong. And I'm aware that the questions I have are very basic, I'm a little embarrassed to ask these simple questions. Please excuse me. I'm 43 years old and had c programming in college 20 years ago. I'm pretty good with HTML and CSS but I'm lacking in a lot of areas. Hope someone can help me with this. Thanks.

Categories

Resources