Utils for javascript

6 minute read

The following codes are the functions that I’ve frequently used in my project. I’d like to copy and paste these codes to save my time from my repetitive jobs. It can be modified any time if necessary.

// --------------------------------------------------------
// show object for debugging
// --------------------------------------------------------
function showObject(obj)
{
    var output = '';
    for (var property in obj) {
        output += property + ' : [' + obj[property] + ']\n';
    }   
    alert(output);
}

// --------------------------------------------------------
// replaceAll prototype
// --------------------------------------------------------
String.prototype.replaceAll = function (org, dest) {
    return this.split(org).join(dest);
}

// --------------------------------------------------------
// Trim
// --------------------------------------------------------
function trim(Value) {
    return Value.replace(/(^\s*)|(\s*$)/gi, "");
}

// --------------------------------------------------------
// Check numeric
// --------------------------------------------------------
function isNumeric(num){
    return !isNaN(num)
}

// --------------------------------------------------------
// get current date format
// --------------------------------------------------------
function getCurrentDate() {
    var _time = new Date();
    var cur_date = _time.toISOString().substring(0, 10) + " " + _time.toTimeString().substring(0, 8);
    return cur_date;
}

function getStringDate(_time) {
    var cur_date = _time.toISOString().substring(0, 10) + " " + _time.toTimeString().substring(0, 8);
    return cur_date;
}

function convertUTCDateToLocalDate(strUTCTime) {
    var _elsp = Date.parse(strUTCTime);
    var _time = new Date();
    _time.setTime(Number(_elsp));
    return _time.toISOString().substring(0, 10) + " " + _time.toTimeString().substring(0, 8)
}

function convertUTCDateToLocalTime(strUTCTime) {
    var _elsp = Date.parse(strUTCTime);
    var _time = new Date();
    _time.setTime(Number(_elsp));
    return _time.toTimeString().substring(0, 8)
}

// --------------------------------------------------------
// formatting time
// --------------------------------------------------------
function formatDiffTime(tm)
{
    var rtime = Number(tm);
    var rtn = "";
    var _hour = 0;
    var _min = 0;
    var _sec = 0;

    // HOUR
    if (rtime > 3600) {
        _hour = Math.round(rtime/3600);
        rtime = rtime%3600;            
    }

    // MINUTE
    if (rtime > 60)
    {
        _min = Math.round(rtime/60);
        rtime = rtime%60;
    }

    // SECOND
    _sec = rtime;

    // FORMATTING
    if (_hour > 0) // No padding
        rtn = _hour + ":" + zeroPadding(_min, 2) + ":" + zeroPadding(_sec, 2);
    else if (_min > 0)
        rtn = _min + ":" + zeroPadding(_sec, 2);
    else
        rtn = _sec; // No padding

    return rtn;
}

// --------------------------------------------------------
// ZeroPadding
// --------------------------------------------------------
function zeroPadding(num, len)
{
    var result = num.toString();
    var pad = len - result.length;
    while (pad > 0) {
        result = '0' + result;
        pad--;
    }   
    return result;
}

// --------------------------------------------------------
// get parameter name
// --------------------------------------------------------
function getParameterByName(url, name) {
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(url);
    var result = match && decodeURIComponent(match[1].replace(/\+/g, ' '));
    if (!result) return '';
    return result;
}


// --------------------------------------------------------
// Load image from url
// --------------------------------------------------------
function loadImageFromUrl(url, width, height) {
    var deferred = $.Deferred();
    var img = new Image();

    img.setAttribute('crossOrigin', 'anonymous');
    img.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = width; // cf. this.width
        canvas.height = height; // cf. this.height

        var ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0);

        var dataURL = canvas.toDataURL("image/png");
        deferred.resolve(dataURL);
    };
    img.onerror = function () {
        deferred.reject();
    };

    img.src = url;

    return deferred.promise();
}

// --------------------------------------------------------
// get thumbnail from image
// --------------------------------------------------------
function getThumbnailFromImage(image, width, height) {

    // create an off-screen canvas
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');

    // set its dimension to target size
    canvas.width = width;
    canvas.height = height;

    // draw source image into the off-screen canvas:
    try {
        ctx.drawImage(image, 0, 0, width, height);
    } catch (e) {
        return null;
    }

    // encode image to data-uri with base64 version of compressed image
    return canvas.toDataURL();
}

// --------------------------------------------------------
// get thumbnail from uri
// --------------------------------------------------------
function getThumbnailFromDataUri(dataUri, width, height) {
    var canvas = document.createElement('canvas');
    var image = new Image();
    image.src = dataUri;
    var context = canvas.getContext('2d');
    var vertSquashRatio = detectVerticalSquash(image);
    if (vertSquashRatio < 1) {
        canvas.width = width * vertSquashRatio;
        canvas.height = height * vertSquashRatio;
        context.drawImage(image, 0, 0, width * vertSquashRatio, height);
    } else {
        canvas.width = width * vertSquashRatio;
        canvas.height = height * vertSquashRatio;
        context.drawImage(image, 0, 0, width, height);
    }

    return canvas.toDataURL();
}

// --------------------------------------------------------
// Refresh DOM
// --------------------------------------------------------
function refreshDOM(element) {
    var disp = element.style.display;
    element.style.display = 'none';
    var trick = element.offsetHeight;
    element.style.display = disp;
};

// --------------------------------------------------------
// A replacement for context.drawImage (args are for source and destination).
// --------------------------------------------------------
function drawImageIOSFix(ctx, img, sx, sy, sw, sh, dx, dy, dw, dh) {
    var vertSquashRatio = detectVerticalSquash(img);
    // Works only if whole image is displayed:
    // ctx.drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh / vertSquashRatio);
    // The following works correct also when only a part of the image is displayed:
    ctx.drawImage(img, sx * vertSquashRatio, sy * vertSquashRatio,
                       sw * vertSquashRatio, sh * vertSquashRatio,
                       dx, dy, dw, dh);
}

/**
 * Detecting vertical squash in loaded image.
 * Fixes a bug which squash image vertically while drawing into canvas for some images.
 * This is a bug in iOS6 devices. This function from https://github.com/stomita/ios-imagefile-megapixel
 * 
 */
function detectVerticalSquash(img) {
    var iw = img.naturalWidth, ih = img.naturalHeight;
    var canvas = document.createElement('canvas');
    canvas.width = 1;
    canvas.height = ih;
    var ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0);
    var data = ctx.getImageData(0, 0, 1, ih).data;
    // search image edge pixel position in case it is squashed vertically.
    var sy = 0;
    var ey = ih;
    var py = ih;
    while (py > sy) {
        var alpha = data[(py - 1) * 4 + 3];
        if (alpha === 0) {
            ey = py;
        } else {
            sy = py;
        }
        py = (ey + sy) >> 1;
    }
    var ratio = (py / ih);
    return (ratio === 0) ? 1 : ratio;
}

// --------------------------------------------------------
// calculate distance from GPS
// --------------------------------------------------------
function calculateDistance(lat1, lon1, lat2, lon2) {
    var radlat1 = Math.PI * lat1 / 180
    var radlat2 = Math.PI * lat2 / 180
    var theta = lon1 - lon2
    var radtheta = Math.PI * theta / 180
    var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
    dist = Math.acos(dist)
    dist = dist * 180 / Math.PI
    dist = dist * 60 * 1.1515
    //if (unit == "K") { dist = dist * 1.609344 }
    //if (unit == "N") { dist = dist * 0.8684 }
    dist = dist * 1.609344 * 1000;
    return dist.toFixed(1) + "m"
}

// --------------------------------------------------------
// Draw and Rotate
// --------------------------------------------------------
function drawLine(ax, ay, bx, by) {
    if (ay > by) {
        bx = ax + bx;
        ax = bx - ax;
        bx = bx - ax;
        by = ay + by;
        ay = by - ay;
        by = by - ay;
    }
    var calc = Math.atan((ay - by) / (bx - ax));
    calc = calc * 180 / Math.PI;
    var length = Math.sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by));
    document.body.innerHTML += "<div id='line' style='height:" + length + "px;width:1px;background-color:black;position:absolute;top:" + (ay) + "px;left:" + (ax) + "px;transform:rotate(" + calc + "deg);-ms-transform:rotate(" + calc + "deg);transform-origin:0% 0%;-moz-transform:rotate(" + calc + "deg);-moz-transform-origin:0% 0%;-webkit-transform:rotate(" + calc + "deg);-webkit-transform-origin:0% 0%;-o-transform:rotate(" + calc + "deg);-o-transform-origin:0% 0%;'></div>"
}

function rotateX(a, b, x, y, degree) {
    var radian = Math.PI * degree / 180;
    return (x - a) * Math.cos(radian) - (y - b) * Math.sin(radian);
}

function rotateY(a, b, x, y, degree) {
    var radian = Math.PI * degree / 180;
    return (x - a) * Math.sin(radian) + (y - b) * Math.cos(radian);
}

// --------------------------------------------------------
// Youtube
// --------------------------------------------------------
function getYoutubeIframeUrl(url) {
    if (url) return url.replace('://youtu.be', '://www.youtube.com/embed');
    else return url;
}

function getYoutubeEmbedUrl(url) {
    if (url) return url.replace('://youtu.be', '://www.youtube.com/v');
    else return url;
}

function getYoutubeThumbnailUrl(url) {
    var newurl = url;
    if (newurl) {
        newurl = url.replace('://youtu.be', '://img.youtube.com/vi');
        newurl = newurl + "/0.jpg";
    }
    return newurl;
}

// --------------------------------------------------------
// replace new line
// --------------------------------------------------------
function convertNewline(str) {
    if (!str) return str;
    var result = str.replace(/\\r\\n/g, "<br />");
    result = result.replace(/\n/g, "<br />");
    return result;
}

// --------------------------------------------------------
// check email validation
// --------------------------------------------------------
function checkEmailFormat(email) {
    if (email.indexOf('@') < 0)
        return false;
    if (email.indexOf('.') < 0)
        return false;
    return true;
}

// --------------------------------------------------------
// User masking
// --------------------------------------------------------
function getUserMasking(user) {

    var result = "***";

    if (user) {
        if (user.length > 4) {
            result = user.substr(0, 4) + '***';
        } else {
            result = user + '***';
        }
    }
    return result;
}

Leave a comment