zaagan
9/26/2017 - 5:35 AM

Javascript Codex

Javascript handy snippets


/* Sample return value : 53228 */
export function getRandomNumber() {
    return Math.floor(Math.random() * 0xFFFF);
}


/* Sample return value : 45935663 */
export function getUniqueNumber(length) {

    if (!length)
        length = 8;
    let timestamp = +new Date;
    let ts = timestamp.toString();
    let parts = ts.split("").reverse();
    let id = "";
    let _getRandomInt = function (min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    for (let i = 0; i < length; ++i) {
        let index = _getRandomInt(0, parts.length - 1);
        id += parts[index];
    }

    return id;
}

/* Sample return value : jmixpdg9 */
export function getUniqueName() {
    return (new Date().getTime()).toString(36);
}
// SOURCE: https://jsfiddle.net/311aLtkz/
// https://stackoverflow.com/a/9851769

    // Opera 8.0+
    var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;

    // Firefox 1.0+
    var isFirefox = typeof InstallTrigger !== 'undefined';

    // Safari 3.0+ "[object HTMLElementConstructor]" 
    var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);

    // Internet Explorer 6-11
    var isIE = /*@cc_on!@*/false || !!document.documentMode;

    // Edge 20+
    var isEdge = !isIE && !!window.StyleMedia;

    // Chrome 1+
    var isChrome = !!window.chrome && !!window.chrome.webstore;

    // Blink engine detection
    var isBlink = (isChrome || isOpera) && !!window.CSS;

var output = 'Detecting browsers by ducktyping:<hr>';
output += 'isFirefox: ' + isFirefox + '<br>';
output += 'isChrome: ' + isChrome + '<br>';
output += 'isSafari: ' + isSafari + '<br>';
output += 'isOpera: ' + isOpera + '<br>';
output += 'isIE: ' + isIE + '<br>';
output += 'isEdge: ' + isEdge + '<br>';
output += 'isBlink: ' + isBlink + '<br>';
document.body.innerHTML = output;
// SOURCE: https://www.nczonline.net/blog/2009/07/28/the-best-way-to-load-external-javascript/
function loadScript(url, callback){

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
    
    
    
  <script type="text/javascript" src="http://your.cdn.com/first.js"></script>
  <script type="text/javascript">
loadScript("http://your.cdn.com/second.js", function(){
    //initialization code
});
</script>
    
}

// ------------------------------------------------------------------------------
//Upper Case
ToTitleCase: function(str) {
    return str.replace(/\w\S*/g, function (txt) { 
      return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); 
    });
},
// ------------------------------------------------------------------------------


// ------------------------------------------------------------------------------
// Trim
String.prototype.trim = function(){
    return this.replace(/^s+|s+$/g, "");
};
// ------------------------------------------------------------------------------


// ------------------------------------------------------------------------------
// Removes any white space to the right and left of the string
function trim(str) {
    return str.replace(/^\s+|\s+$/g, "");
}
// ------------------------------------------------------------------------------


// ------------------------------------------------------------------------------
// Removes any white space to the left of the string
function ltrim(str) {
    return str.replace(/^\s+/, "");
}
// ------------------------------------------------------------------------------


//Removes any white space to the right of the string
function rtrim(str) {
    return str.replace(/\s+$/, "");
}
// ------------------------------------------------------------------------------


// ------------------------------------------------------------------------------
//Truncate a string to a given length
function truncate(str, len) {
    if (str.length > len) {
        str = str.substring(0, len);
    }
    return str;
};
// ------------------------------------------------------------------------------


// ------------------------------------------------------------------------------
// Return a string only containing the letters a to z
function onlyLetters(str) {
    return str.toLowerCase().replace(/[^a-z]/g, "");
};
// ------------------------------------------------------------------------------


// ------------------------------------------------------------------------------
// Return a string only containing the letters a to z and numbers
function onlyLettersNums(str) {
    return str.toLowerCase().replace(/[^a-z,0-9,-]/g, "");
};
// ------------------------------------------------------------------------------


// ------------------------------------------------------------------------------
// String Interpolation
let count = 3;
console.log(`I have ${count} pencils`);
// ------------------------------------------------------------------------------


var data = `<?xml version=\"1.0\" encoding=\"utf-8\"?>
           <string xmlns=\"http://tempuri.org/\">Somedata</string>`;

var xmlParser = new DOMParser();
var doc = xmlParser.parseFromString(data, 'text/xml');
var newData = doc.getElementsByTagName('string')[0].childNodes[0].nodeValue;
return newData;

//https://stackoverflow.com/questions/1988349/array-push-if-does-not-exist

// SOURCE: https://stackoverflow.com/a/36683363
// Code Snippet : https://stackoverflow.com/questions/1988349/array-push-if-does-not-exist

var newItem = "OLD_ITEM_1";
var array = ["OLD_ITEM_1", "OLD_ITEM_2"];

array.indexOf(newItem) === -1 ? 
array.push(newItem) : console.log("This item already exists");

console.log(array)


//------------------------------------------------------------------------
// Find Max Min
var  numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
var maxInNumbers = Math.max.apply(Math, numbers);
var minInNumbers = Math.min.apply(Math, numbers);
//------------------------------------------------------------------------


//------------------------------------------------------------------------
// Removes an item from a given array
function removeArrayItem(arr, item) {
    var i = 0;
    while (i < arr.length) {
        if (arr[i] == item) {
            arr.splice(i, 1);
        } else {
            i++;
        }
    }
};
//------------------------------------------------------------------------



//------------------------------------------------------------------------
// Check if the array 'a' contains a given object 'obj'
function contains(a, obj) {
    var i = a.length;
    while (i--) {
        if (a[i] === obj) {
            return true;
        }
    }
    return false;
};
//------------------------------------------------------------------------


//------------------------------------------------------------------------
// The index of an item - Javascript 1.6+
['glenn','john'].indexOf('john')  returns 2
//------------------------------------------------------------------------



var startDate = "2018-01-18"

var dt= Date.parse(startDate);   
// Here dt = 1516233600000

var newDate= new Date(dt) 
//OUTPUT:  Date 2018-01-18T00:00:00.000Z
  
  

// Validate Links
ValidateLink: function (s) {
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
    return regexp.test(s);
},
// Source : https://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object
//          https://stackoverflow.com/a/32108184
var a = {}

// because Object.keys(new Date()).length === 0;
// we have to do some additional check

// [ ECMA 5+ ]
Object.keys(obj).length === 0 && obj.constructor === Object

// [ Pre-ECMA 5 ]
function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }

    return JSON.stringify(obj) === JSON.stringify({});
}

// [ JQuery ]
jQuery.isEmptyObject({}); // true


// [ LODASH ]
_.isEmpty({}); // true


// [ UNDERSCORE ]
_.isEmpty({}); // true


// [ Hoek ]
Hoek.deepEqual({}, {}); // true


// [ ExtJS ]
Ext.Object.isEmpty({}); // true


// [ AngularJS v1 ]
angular.equals({}, {}); // true


// Ramda
R.isEmpty({}); // true
// SOURCE: 
// 1. https://console.spec.whatwg.org/
// 2. https://tinyurl.com/y9qbzp35

window.console.log('This works')
console.log('So does this')

// -------------------------------------------------
//String Substitutions 
Input: console.log('string %s', 'substitutions')
//Output: string substitutions
// -------------------------------------------------

// -------------------------------------------------
// Numbers
console.log('int: %d, floating-point: %f', 1, 1.5)
// Output: int: 1, floating-point: 1.500000
console.log('int: %d, floating-point: %.1f', 1, 1.5)
// Output:int: 1, floating-point: 1.5
// -------------------------------------------------

// -------------------------------------------------
// Objects
const a = 'substitutions';
console.log(`bear: ${a}`);
// bear: substitutions
// -------------------------------------------------

// -------------------------------------------------
// Colors
const success = [
 'background: green',
 'color: white',
 'display: block',
 'text-align: center'
].join(';');

const failure = [
 'background: red',
 'color: white',
 'display: block',
 'text-align: center'
].join(';');

console.info('%c /dancing/bears was Successful!', success);
console.log({data: {
 name: 'Bob',
 age: 'unknown'
}}); // "mocked" data response

console.error('%c /dancing/bats failed!', failure);
console.log('/dancing/bats Does not exist');
console.log('%cred %cblue %cwhite','color:red;','color:blue;', 'color: white;')
// -------------------------------------------------

// -------------------------------------------------
// Assert
let isTrue = false;
console.assert(isTrue, 'This will display');
isTrue = true;
console.assert(isTrue, 'This will not');
// -------------------------------------------------

// -------------------------------------------------
// Table
console.table(['Javascript', 'PHP', 'Perl', 'C++']);

const superhero = { 
    firstname: 'Peter',
    lastname: 'Parker',
}
console.table(superhero)

// For Chrome 
console.table([['Javascript', 'PHP', 'Perl', 'C++']]);

const superhero = { 
    firstname: 'Peter',
    lastname: 'Parker',
}
console.table([superhero]); 
// -------------------------------------------------

// -------------------------------------------------
// GROUP
console.group();
console.log('I will output');
console.group();
console.log('more indents')
console.groupEnd();
console.log('ohh look a bear');
console.groupEnd();
// -------------------------------------------------

// -------------------------------------------------
// Time
console.time('id for timer')
console.timeEnd('id for timer')
// -------------------------------------------------
// ---------------------------------------------------------------------
// A palindrome is a word that reads the same backward or forward.
// Write a function that checks if a given word is a palindrome. Character case should be ignored.
// function isPalindrome(word)
// For example, isPalindrome("Deleveled") should return true as character case should be ignored, 
// resulting in "deleveled", which is a palindrome since it reads the same backward and forward.
// ---------------------------------------------------------------------


// ---------------------------------------------------------------------
// [APPROACH 1]
function palindrome(text) {
  // Split, reverse and join string to get reversed text
  var reversedText  = text.toLowerCase().split('').reverse().join('');
  return text === reversedText;
}
// ---------------------------------------------------------------------


// ---------------------------------------------------------------------
// [APPROACH 2] Cons: Too costly
function palindrome(text) {
  // Split text into array of characters
  let charArray = text.toLowerCase().split('');

  // Loop through every character and compare with the
  // character in its corresponding position if the string
  // was reversed. Then store the result
  let result = charArray.every((letter, index) => {
    return letter === charArray[charArray.length - index - 1];
  });

  // Return the result of the evaluation
  return result
}
// ---------------------------------------------------------------------


// ---------------------------------------------------------------------
// [ Approach 3]
function isPalindrome(word)
{
  const iter = [...word.toLowerCase()];
  for (let char of iter) {
    if (char !== iter.pop()) { return false}
  }
  
  return true
}
// ---------------------------------------------------------------------


// ---------------------------------------------------------------------
// Other approaches >
// https://stackoverflow.com/questions/22111507/how-to-write-palindrome-in-javascript
// Topic: Numbers

// ------------------------------------------------------------------ 
// Shuffle
var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
numbers = numbers.sort(function(){ return Math.random() - 0.5});

/* the array numbers will be equal for example to
[120, 5, 228, -215, 400, 458, -85411, 122205]  */
// ------------------------------------------------------------------ 


// ------------------------------------------------------------------ 
// Is String
function isString(obj) {
    return typeof (obj) == 'string';
};
// ------------------------------------------------------------------ 


// ------------------------------------------------------------------ 
// Is URL
function isUrl (obj) {
    if(isString(obj)){
        var re = new RegExp("^(http|https)\://([a-zA-Z0-9\.\-]+(\:" +
            "[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|" +
            "[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2" +
            "[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\." +
            "(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|" +
            "[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]" +
            "{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z" +
            "0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name" +
            "|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-z" +
            "A-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$");
        return obj.match(re);
    }else{
        return false;
    }
};
// ------------------------------------------------------------------ 


// ------------------------------------------------------------------ 
// Is Email
function isEmail(obj) {
    if(isString(obj)){
        return obj.match(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/ig);
    }else{
        return false;
    }
};
// ------------------------------------------------------------------ 


// ------------------------------------------------------------------ 
// Is Int
function isInt(obj) {
    var re = /^\d+$/;
    return re.test(obj);
};
// ------------------------------------------------------------------ 


// ------------------------------------------------------------------ 
// Is Number
function isNumber(n){
    return !isNaN(parseFloat(n)) && isFinite(n);
}
// ------------------------------------------------------------------ 


// ------------------------------------------------------------------ 
// Is Array
function isArray(obj) {
    return obj && !(obj.propertyIsEnumerable('length'))
        && typeof obj === 'object'
        && typeof obj.length === 'number';
};

// Is Array 2
function isArray(obj){
    return Object.prototype.toString.call(obj) === '[object Array]' ;
}
// OR
Array.isArray(obj);
// ------------------------------------------------------------------ 


// ------------------------------------------------------------------ 
// Round Numbers
var num =2.443242342;
num = num.toFixed(4);  // num will be equal to 2.4432
// ------------------------------------------------------------------ 


function sum(...theArgs) {
  return theArgs.reduce((previous, current) => {
    return previous + current;
  });
}

console.log(sum(1, 2, 3));
// expected output: 6

console.log(sum(1, 2, 3, 4));
// expected output: 10
var a, b, rest;
[a, b] = [10, 20];

console.log(a);
// expected output: 10

console.log(b);
// expected output: 20

[a, b, ...rest] = [10, 20, 30, 40, 50];

console.log(rest);
// expected output: [30,40,50]