Thursday, April 14, 2016

JavaScript: Get Random Number Between A Given Range of 2 Numbers

Ever had that moment where you needed a random number between two given numbers, but find it hard to get exactly what you're looking for a regular and repeated basis? Quite often, if you go searching, you may see something like:

function getRandomIntInclusive(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

The previous is the most common method and can be found at @ developer.mozilla.org. The problem with this method is it's lack of involvement. For instance, what if you need a random decimal value between 1 and 2? What if you need to never include the minimum and maximum in the range? What if you need to ensure they are always a possibility?

There are countless reasons as to why this one method just won't do, which is why there are more than one methods @ developer.mozilla.org. But what you just want one simple method you can use regularly for most every possible instance you can think of?

Well, you're in the right place!

I've created a method and provided several ways of adding it to your site that makes everything about generating random numbers so much easier! - [Find @ github]

First, what it does:

If you simply need to get a random number within a given range, including the possible minimum and maximum, then simply call the method and pass the smallest number as the first parameter and the largest number as the second parameter, such as:

getRandInt(1, 2) = 1.2783833924813244

However, if you need to ensure it's ALWAYS a whole number, then simply add a third parameter of true!

getRandInt(1, 2, true) = 1

Or perhaps you need a set number of decimal places [Currently only supports up to 20]

getRandInt(1, 2, 19) = 1.1342048875680916797

Or maybe you need to ensure it's ONLY between the range and NEVER includes the min and max given, then simply reverse the parameters!

getRandInt(2, 1) = 1.3221148112756618

It's all pretty simple!


Now, for implementation ... can you say "EZ"?

Just how easy you ask? Well, I've taken the guess work out of most everything!

For a simple Global Method you can call anywhere, such as getRandInt(1, 2); simply add the following to your <head>

<script src="https://rawgit.com/JDMcKinstry/JavaScript-getRandInt/master/window.getRandInt.min.js" type="text/javascript"></script>

Or If you'd like to add it to the Math Object for a more familiar use, then include the following in your <head>

<script src="https://rawgit.com/JDMcKinstry/JavaScript-getRandInt/master/Math.getRandInt.min.js" type="text/javascript"></script>

OR[¡BONUS TIME!] If you want to use it as a jQuery method, then include the following in your <head> BUT make sure it comes after your jQuery inclusion!

<script src="https://rawgit.com/JDMcKinstry/JavaScript-getRandInt/master/jQuery.getRandInt.js" type="text/javascript"></script>

If you'd like to play around with it a bit and test it out, then check out this jsFiddle!

NOW GO FORTH, AND GET RANDOM!

Tuesday, February 9, 2016

EPIC RANDOM STRING GENERATOR 9001!!! IT'S OVER 9000!!!

BEHOLD! THE ULTIMATE RANDOM STRING MAKER 9001!

Do you want random strings to the extreme?! Do you crave the random goodness in favor of something better than what you see elsewhere?! Are you tired of all these weak answers out there saying they solve this problem or that without having a problem of their own?! ARE YOU MISSING A COMBO OF NUMBERS, AND UPPER AND LOWER CASE LETTERS?! Then I've got the juice for you!
¡UPDATE! Now improved performance of random string request having a length greater than 23! Was a slight issue before where long strings might not always be number requested, if request was greater than 23. However, NO LONGER A PROBLEM! ¡ENJOY!
/* COPY && PASTE */
function epicRandomString(b){for(var a=(Math.random()*eval("1e"+~~(50*Math.random()+50))).toString(36).split(""),c=3;c<a.length;c++)c==~~(Math.random()*c)+1&&a[c].match(/[a-z]/)&&(a[c]=a[c].toUpperCase());a=a.join("");a=a.substr(~~(Math.random()*~~(a.length/3)),~~(Math.random()*(a.length-~~(a.length/3*2)+1))+~~(a.length/3*2));if(24>b)return b?a.substr(a,b):a;a=a.substr(a,b);if(a.length==b)return a;for(;a.length<b;)a+=epicRandomString();return a.substr(0,b)};
/* COPY && PASTE */

EASY TO USE!!!

var rand = epicRandomString();
/*  OR IF YOU NEED A SET LENGTH!    */
var rand = epicRandomString(10);
Tested 1 MILLION TIMES! and found 0! duplicates with no set length, and only 14! duplicates with a set length of 10!

JavaScript to get Aspect Ratio

The following is just a simple calclator for gaining Aspect Ratio.

This will allow you to find 4th value if needed, or simply tell you what the aspect ratio between two sets of measurements is, provided they match. An AR of 4/3 isn't going to match 9/7, thus you'd get a false return. In this way, you can check that an Aspect Ratio was adjusted correctly.

Easy Uses!

  • aspectRatioHD({ "height": 600, "width": 800 }, { "height": 1200 }); // would return 1600, which would be your new "width"
  • aspectRatioHD({ "height": 600, "width": 800 }, { "width": 1600 }); // would return 1200, which would be your new "height"
  • aspectRatioHD({ "height": 600 }, { "height": 1200, "width": 1600 }); // would return 800, which would be your new "width"
  • aspectRatioHD({ "width": 800 }, { "height": 1200, "width": 1600 }); // would return 600, which would be your new "height"
  • aspectRatioHD({ "height": 600, "width": 800 }, { "height": 1200, "width": 1600 }); // would return [4,3], The spect Ratio in Array Format being [W,H]
  • aspectRatioHD({ "height": 600, "width": 800 }, { "height": 1200, "width": 1600 }); // would return [4,3], The spect Ratio in Array Format being [W,H]
  • aspectRatioHD({ "height": 3, "width": 4 }, { "height": 7, "width": 9 }); // would return false, since these 2 aspect ratios do not match

Code

function aspectRatioHD(){if(2==arguments.length){var d=function(a){a=parseFloat((""+a).replace(/[^0-9.]/g,""));return a==a?a:void 0},a=function(a){var b={},c;for(c in a)if(a.hasOwnProperty(c))switch(c.toLowerCase()){case "height":b.h=d(a[c]);break;case "width":b.w=d(a[c])}if("number"!=typeof b.h||b.h!=b.h)b.h=void 0;if("number"!=typeof b.w||b.w!=b.w)b.w=void 0;return b},b=a(arguments[0]),a=a(arguments[1]);if(b.w&&b.h&&a.w&&a.h)return Math.round(a.w/a.h*100)/100==Math.round(b.w/b.h*100)/100?(b=function e(a,
b){return b?e(b,a%b):a},b=b(a.w,a.h),[a.w/b,a.h/b]):a.w/a.h==b.w/b.h;if(b.w&&b.h&&!a.w&&a.h)return Math.round(b.w/b.h*a.h);if(b.w&&b.h&&a.w&&!a.h)return Math.round(a.w/(b.w/b.h));if(!b.w&&b.h&&a.w&&a.h)return Math.round(a.w/a.h*b.h);if(b.w&&!b.h&&a.w&&a.h)return Math.round(b.w/(a.w/a.h))}else throw Error("Invalid Amount of Arguments. Must have 2 arguments such as: [{height:1,width:2},{height:3}]");};

Go play with it here!

Or see the Result below

HTML5 JavaScript localStorage Helper!!! Beyond a how to; "localStorageHelper" a clear and simple way to use Local Storage!

Just a quick and simple class for working with `localStorage`! Extremely easy to use!

Easy Uses!

Simply assign:

var lsh = new localStorageHelper()

And go!
  • lsh.isAvailable; // after class called, becomes boolean property
  • lsh.get(); // retrieve an Object of ALL available localStorage items
  • lsh.get('keyName'); // retrieve value for storage item having passed key name
  • lsh.set('keyName', 'assorted value'); // value can be ALMOST anything!
  • lsh.remove('keyName'); // seeks to remove storage item having key name
  • lsh.clear(); // remove ALL storage items
  • lsh.on('eventName', callback); // set a callback method to preform when event is fired
  • lsh.off('eventName', callback); // attempts to remove callback from list of handlers on given event

Oh, and did I mention events?!

  • lsh.on('get', function(e) { /* e={ eventType: "get", key: "keyName", url: "currentAddress", value: "the value" } */ }); // do work whenever get is called AND something is actually retrieved
  • lsh.on('set', function(e) { /* e={ eventType: "set", key: "keyName", success: bool, url: "currentAddress", value: "the value" } */ }); // do work when new value is set
  • lsh.on('remove', function(e) { /* e={ eventType: "remove", key: "keyName", success: bool, url: "currentAddress", value: "the value" } */ }); // do work when value is removed
  • lsh.on('clear', function(e) { /* e={ eventType: "clear", success: bool, url: "currentAddress" } */ }); // do work when all values are cleared

Code

function localStorageHelper() {
 // variable for this class
 var $this = this;
 
 // set whether if localstorage is isAvailable
 this.isAvailable = function() {
  try { return 'localStorage' in window && window['localStorage'] !== null; }
  catch (e) { return !1 }
 }();
 
 // HELPERS
 this.keyExists = function(key) { return this.isAvailable && key !== void 0 && localStorage.key(key); }
 this.keyAtIndex = function(i) { return this.isAvailable ? localStorage.key(i) : void 0; }
 // returns an array of keys
 this.getKeys = function() {
  if (!this.isAvailable) return void 0; 
  var k = []; 
  for (var i=0;i<localStorage.length;i++) k.push(localStorage.key(i)); 
  return k;
 }
 // returns array of values
 this.getValues = function() {
  if (!this.isAvailable) return void 0; 
  var v = []; 
  for (var i=0;i<localStorage.length;i++) v.push(this.get(localStorage.key(i))); 
  return v;
 }
 
 // get/set/remove/clear local storage item(s) and fire get event
 this.get = function(key) {
  if (this.isAvailable) {
   if (typeof key === "number") key = this.keyAtIndex(key);
   if (this.keyExists(key)) {
    var val;
    try { return val = JSON.parse(localStorage.getItem(key)); }
    catch(err) { return val = localStorage.getItem(key); }
    finally { this.onGet.fire(key, val); }
   }
   else if (key === void 0) { // if no key provided, then assume "get all" and return Object of all items in localStorage
    var a = {};
    try {
     for (var i=0;i<localStorage.length;i++) if (this.keyAtIndex(i)) a[this.keyAtIndex(i)] = this.get(this.keyAtIndex(i));
     return a;
    }
    finally { this.onGet.fire(key, a); }
   }
  }
  return void 0;
 }
 this.set = function(key, value) {
  if (this.isAvailable) this.onSet.fire(key, value, function() {
   try {
    try { localStorage.setItem(key, JSON.stringify(value)); }
    catch(err) { localStorage.setItem(key, value); }
    return true;
   }
   catch(err) {}
   return false;
  }());
  return $this;
 }
 this.remove = function(key) {
  if (this.isAvailable && this.keyExists(key)) this.onRemove.fire(key, this.get(key), function() {
   try { localStorage.removeItem(key); return true; }
   catch(err) { return false; }
  }());
  return $this;
 }
 this.clear = function() {
  if (this.isAvailable) this.onClear.fire(null, null, function() {
   try { localStorage.clear(); return true; }
   catch(err) { return false; }
  }());
  return $this;
 }
 
 // EVENTS
 function setEvent(eType) {
  var eventName = "on" + (eType.charAt(0).toUpperCase() + eType.slice(1)),
   ret = function(handler) {
    if (typeof handler == "function") {
     var $handlers = this[eventName].handlers,
      strHandler = handler.toString().replace(/ |\t|\r|\n/ig, '');
     for (var x in $handlers) if (strHandler == $handlers[x].toString().replace(/ |\t|\r|\n/ig, '')) return this[eventName];
     $handlers.push(handler);
    }
    return this[eventName];
   }
  ret.fire = function(k, v, s) {
   var $handlers = this.handlers,
    args = { eventType: eType };
   if (k !== undefined && k !== null) args.key = k
   if (v !== undefined && v !== null) args.value = v
   if (s !== undefined && s !== null) args.success = s
   args.url = window.location.toString();
   for (var x in $handlers) $handlers[x].apply($this, [args])
  }
  ret.handlers = [];
  return ret;
 }
 this.on = function(a, b) {
  a = "on" + (a.charAt(0).toUpperCase() + a.slice(1));
  this.hasOwnProperty(a) && this[a].apply($this, [b]);
 };
 this.off = function(a, b) {
  a = "on" + (a.charAt(0).toUpperCase() + a.slice(1));
  if (this.hasOwnProperty(a) && "function" == typeof b) {
   var c = this[a].handlers,
    e = b.toString().replace(/ |\t|\r|\n/ig, ""),
    d;
   for (d in c)
    if (e == c[d].toString().replace(/ |\t|\r|\n/ig, "")) {
     c.splice(d, 1);
     break;
    }
  }
  return $this;
 };
 
 this.onGet = setEvent.apply(this, ['get']);
 this.onSet = setEvent.apply(this, ['set']);
 this.onRemove = setEvent.apply(this, ['remove']);
 this.onClear = setEvent.apply(this, ['clear']);
 
 // Final summary, check if LS is even available, if not, throw error and process callback method if provided
 if (!this.isAvailable) {
  var msg = "[localStorage] is unavailble!";
  if (arguments.length && typeof arguments[0] == "function") arguments[0].apply($this, [{ isAvailable: this.isAvailable, Error: msg }]);
  throw new Error(msg);
 }
 
 return this;
}

Go play with it here!