Note that there are some explanatory texts on larger screens.

plurals
  1. POBetter way to write this particular function in JavaScript
    text
    copied!<p>I'm beginning my journey with JavaScript and programming in general. Not having many developers around I could ask how to do this or do that i'm learning by doing however I'd like some pro's to look around my code and tell me how bad it is.</p> <p>Any comments for a Noob will be appreciated. Thank you in advance! I know there is probably zillion such classes but I want to learn from scratch and not reuse someones code at this level of my knowledge.</p> <p>this function returns colors in rgba(r,g,b,a) or rgb(r,g,b) format taking a value for each channel or a random value if "random" is a parameter for an color channel:</p> <p><code>someColor = nutils.getNewColor(100,200,"random","random");</code></p> <p>will return a string in format:</p> <p><code>"rgba(100,232,0.12)"</code> or <code>"rgb(100,200,234)"</code> if no alpha is passed</p> <p>Here is the code I wrote:</p> <p><code> </p> <pre><code>window.utils.getNewColor = function (rRange, gRange, bRange, alpha) { function rValue() { return Math.round(Math.random() * 255); } if (!rRange == undefined || rRange == null || typeof rRange === 'string' &amp;&amp; rRange == "random") { rRange = rValue(); } if (!gRange == undefined || gRange == null || typeof gRange === 'string' &amp;&amp; gRange == "random") { gRange = rValue(); } if (!bRange == undefined || bRange == null || typeof bRange === 'string' &amp;&amp; bRange == "random") { bRange = rValue() } if (typeof alpha === 'string' &amp;&amp; alpha == "random") { alpha = Math.round(Math.random() * 100) / 100 return "rgba(" + rRange + "," + gRange + "," + bRange + "," + alpha + ")"; } else if (typeof alpha === 'number' &amp;&amp; alpha &lt; 1) { return "rgba(" + rRange + "," + gRange + "," + bRange + "," + alpha + ")"; } else { return "rgb(" + rRange + "," + gRange + "," + bRange + ")"; } }; </code></pre> <p></code></p> <p><h2>UPDATE</H2></p> <p>After reading your comments I come up with a solution based on @KooilNic advise, however slightly modified to comprehend my lack of understanding ternary operations evaluation.</p> <p>Here is the modified/updated code:</p> <p><code></p> <pre><code>utils.getNewColor = function (rRange, gRange, bRange, alpha) { rRange = rRange || Math.round(Math.random() * 255); gRange = gRange || Math.round(Math.random() * 255); bRange = bRange || Math.round(Math.random() * 255); if (alpha === undefined) { return "rgb(" + [rRange, gRange, bRange].join(',') + ")"; } else { alpha = alpha &amp;&amp; alpha &lt; 1 ? alpha : (Math.round(Math.random() * 100) / 100); return "rgba(" + [rRange, gRange, bRange, alpha].join(',') + ")"; } }; </code></pre> <p></code></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload