jQuery AJAX

I’m sure there’s a perfectly good explanation for why the “always” function has two different signatures – one for requests that were successful and a different one for unsuccessful ones. But whatever their reason, they’re wrong. This is just plain stupid that you don’t know what kind of object the first and third parameters are. But they never asked me before they implemented it, so there’s nothing I can do about it…

var jqXHR = jQuery.ajax(ajaxParams);
jqXHR.done(function(data, textStatus, jqXHR) {});
jqXHR.fail(function(jqXHR, textStatus, errorThrown) {});
jqXHR.always(function(data|jqXHR, textStatus, jqXHR|errorThrown ) { });
The ajaxParams object contains lots of different options - the ones I generally use are as follows:
{
    // absolute or relative
    url: "/path/to/some/url",

    // will you be receiving "json", "html", "text", or "xml" back
    // 99% of the time I use json or html. If json, then the result will already
    // be parsed into a javascript object.
    dataType: "json",

    // what kind of data you are posting
    // 'application/x-www-form-urlencoded; charset=UTF-8' is the default
    contentType: "application/json; charset=utf-8",

    // This one is fun. If you're posting form-urlencoded, then this can 
    // either be a string representing the form post, like name=John&age=34
    // or it can be a javascript object and jQuery will automatically build
    // the string: { name: "John", age: 34 }
    // However, if you are posting JSON, then it needs to be a JSON string (not
    // an object, but the JSON representation of that object):
    // JSON.stringify({ name: "John", age: 34 })
    data: myData
}

There’s a lot more you can do with it – see the documentation.

GZip with Pako

GZip is a super-fast compression technique, usable anywhere. In javascript, you can use the Pako library to compress your data.

Browser

<!DOCTYPE html>
<html>
<head>
    <title>Test Zip</title>
    </head>
    <body>
        <textarea id="inputText" style="width: 90%; height: 300px;"></textarea>
        <textarea id="outputText" style="width: 90%; height: 300px;"></textarea>
        <br>
        <input type="button" value="Go" onclick="go();">
        <script src="https://cdn.jsdelivr.net/pako/1.0.5/pako.min.js"></script>
        <script>
            function go() {
                console.log(document.getElementById("inputText").value.length);
                var compressedBytes = pako.gzip(document.getElementById("inputText").value);

                console.log("compressedBytes: " + compressedBytes.length);

                try {
                   var decompressedText = pako.ungzip(compressedBytes, { to: "string" });
                   document.getElementById("outputText").value = decompressedText;
                } catch (ex) {
                    console.log(ex);
                }
            }
        </script>
    </body>
</html>

NodeJS

const pako = require("pako");

const inputText = `旧団撃健載婚。西住姿要臣市未検成録止記悪転団。稿代江型集対著側込円号乳前爆下集広。稿界版陽更工振火国張産指天支日自果圧見。判社安団自外面用売神農更春日策現管野。線咲破面経速町日止満行直。集禁未化捕併投購加様塗抗録規開各在造能訴。断否界駅小安計注必式面柴。会継内欺受方添条武風復不断撃楽産支。

Hello world, this is a test!

知系締描文民法芸機各共作請始紹論明禁。者注省警権宅急今変埼問何文力。陣済当名屋康慣生用前更測説官類無。早高医教護告野滑綱混着特購加遅代逸通口戦。増再賀期木多合作就勢城析車人出済。訪任人改重江賞需農神書関。市理闘演礼場事付現運違有指的。心秋雄式作意切加県米外限竹真法鮮。足顔漁性倍何買真購話注私紙中際。`;

console.log(inputText);

const compressedBytes = pako.gzip(inputText);

console.log(`compressedBytes: ${compressedBytes.length}`);

try {
   const decompressedText = pako.ungzip(compressedBytes, { to: "string" });
   console.log(decompressedText);
} catch (ex) {
    console.log(ex);
}

Javascript GUID

If you need a GUID in Javascript, here are samples for building your own, either in a browser setting, or using NodeJS where you can easily add more features.

In Browser

function createGuid() {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c == "x" ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

NodeJS

Technically this isn’t a proper GUID, but it is 16 cryptographically-pseudorandom bytes and works just fine if you need something that fits into a Guid/Uniqueidentifier or whatever else you’re calling it.

const crypto = require("crypto");

class Guid {

    constructor(hex) {
        if (typeof hex != "string") {
            throw "Must be a string";
        }
        
        var val = hex.replace(/[^0-9a-fA-F]/g, "").toLowerCase();
        if (val.length != 32) {
            throw "Must be 32 hex characters";
        }

        this._hex = val;
    }

    static newGuid() {

        var bytes = crypto.randomBytes(32);

        for (let i = 0; i < 32; ++i) {
            bytes[i] = (bytes[i] / 16) | 0;
        }

        let i = 0;
        let hex = "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g, function (c) {
            var r = bytes[i++], v = c == "x" ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
        return new Guid(hex);
    }

    toString(format) {
        format = (format || "D");
        let sub = (start, end) => this._hex.substring(start, end);
        switch (format) {
            case "N": return this._hex.toUpperCase();
            case "n": return this._hex;
            case "D": return (`${sub(0, 8)}-${sub(8, 12)}-${sub(12, 16)}-${sub(16, 20)}-${sub(20, 32)}`).toUpperCase();
            case "d": return (`${sub(0, 8)}-${sub(8, 12)}-${sub(12, 16)}-${sub(16, 20)}-${sub(20, 32)}`);
        }
    }
}

module.exports = Guid;

Destructuring in javascript

Used to extract values from arrays and objects and assign to variables, making it easier for callers to see what they need to pass in to the function

"use strict";

// old way:
function PersonOld(options) {
    this.name = options.name;
    this.age = options.age;
    this.height = options.height;
}

// new way:
function PersonNew({ name, age, height }) {
    this.name = name;
    this.age = age;
    this.height = height;
}

// if you want it optional, then set to a default value:
function PersonOptional({ name, age, height } = { name: "Bill", age: 31, height: 23 }) {
    this.name = name;
    this.age = age;
    this.height = height;
}

// you can use defaults within the object:
function PersonDefaults({ name, age = 99, height }) {
    this.name = name;
    this.age = age;
    this.height = height;
}

var options = {name: "John", age: 34, height: 72};
var personOld = new PersonOld(options);
var personNew = new PersonNew(options);

// same output
console.log(personOld);
console.log(personNew);

console.log(new PersonOptional());
console.log(new PersonDefaults({name: "Barry", height: 53}));

Browser Support

No IE support, requires a real browser

SHA hash in NodeJS

const crypto = require("crypto");
const filename = process.argv[2];
const fs = require("fs");

const hash = crypto.createHash("sha256");

const input = fs.createReadStream(filename);
input.on("readable", () => {
    const data = input.read();
    if (data) {
        hash.update(data);
    } else {
        console.log(`${hash.digest("hex")} ${filename}`);
    }
});

Reference

https://nodejs.org/api/crypto.html

Javascript does element have class

If you need to check if an element has a given class, there are a few ways. jQuery has a hasClass function. If you’re limited to users using IE10 or a real browser, then you can use the Element.classList property.

But if you have to cater to old IE users, and aren’t using jQuery, then you can use the following to check to see if an element has a class. Just put this in one of your header script files, before anything that would use it:

if (!Object.prototype.hasClass) {
    Object.prototype.hasClass = function (x) {
        if (!this.className || !this.className.indexOf) {
            return false;
        }
        return (" " + this.className + " ").indexOf(" " + x + " ") >= 0;
    };
}

var elem = document.getElementById("div1");
var hasRed = elem.hasClass("red");

Get Selected Text in Javascript

function getSelectedText() {
    if (window.getSelection) {
        return window.getSelection();
    }
    if (document.getSelection) {
        return document.getSelection();
    }
    if (document.selection) {
        return document.selection.createRange().text;
    } 
    return "";
}

CDN with failover

Loading your scripts from a CDN is generally a good idea, for many reasons. Using a CDN helps load your site faster, possibly use less bandwidth, and reduces costs.

Once in awhile, your CDN may be unavailable, and you want the site to work anyway. For example, if you have an internal intranet application, but your office external internet is down. You can try to use the CDN by default, but if it doesn’t work, you’ll load the script file from your server.

<script type="text/javascript">
    function addScriptToDOM(url) {
        document.write('\x3Cscript type="text/javascript" src="' + url + '">\x3C/script>');
    }
</script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">window.jQuery || addScriptToDOM("/Scripts/jquery-1.11.3.min.js")</script>

call/apply/bind in Javascript

Definition

func.call(thisArg, arg1, arg2, ...)
func.apply(thisArg, [argsArray])
func.bind(thisArg[, arg1[, arg2[, ...]]])

These three functions allow you to attach a function to an object to make it act like a method, where “this” represents the object.

call and apply are identical, except call accepts a dynamic number of parameters, while apply accepts an array of values.

Sample Code

const Line = function() {
    this._spaces = [];
    for (let i = 0; i < 10; ++i) { this._spaces[i] = "."; }

    this.turnOn = function(idx) { this._spaces[idx] = "X"; };
    this.turnOff = function(idx) { this._spaces[idx] = "."; };
    this.toString = function() { return this._spaces.join(""); }
};

const line = new Line();

const turnOnTwo = function (idx1, idx2) {
    this.turnOn(idx1);
    this.turnOn(idx2);
};

console.log(line.toString()); // ..........

call

// "c"all = "c"omma separated parameters
turnOnTwo.call(line, 3, 5);
console.log(line.toString()); // ...X.X....

apply

// "a"pply = "a"rray of items
turnOnTwo.apply(line, [0, 8]);
console.log(line.toString()); // X..X.X..X.

bind

const boundFunction = turnOnTwo.bind(line);
boundFunction(1, 2);
console.log(line.toString()); // XXXX.X..X.

Reference

Browser Requirements

call and apply are available anywhere. bind requires IE9+ or a real browser.

Polyfill

if (!Function.prototype.bind) {
  Function.prototype.bind = function(oThis) {
    if (typeof this !== 'function') {
      // closest thing possible to the ECMAScript 5
      // internal IsCallable function
      throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
    }

    var aArgs   = Array.prototype.slice.call(arguments, 1),
        fToBind = this,
        fNOP    = function() {},
        fBound  = function() {
          return fToBind.apply(this instanceof fNOP
                 ? this
                 : oThis,
                 aArgs.concat(Array.prototype.slice.call(arguments)));
        };

    if (this.prototype) {
      // Function.prototype doesn't have a prototype property
      fNOP.prototype = this.prototype; 
    }
    fBound.prototype = new fNOP();

    return fBound;
  };
}

Array.map

Definition

[].map(function(currVal, idx, arr) { }[, thisArg]);

Sample Code

// Simple
var arr = ["a", "b", "c"];
var helloArr = arr.map(function(x) { return "Hello " + x; });
helloArr.forEach(console.log);

// Using thisArg
var item = { sum: 0 };
var newArray = [1,2,3].map(function(x) { this.sum += x; return x * 10; }, item);
console.log(item.sum); // 6
console.log(newArray); // [10,20,30]

Reference

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Polyfill

if (!Array.prototype.map) {
  Array.prototype.map = function(callback/*, thisArg*/) {
    var T, A, k;
    if (this == null) {
      throw new TypeError('this is null or not defined');
    }
    var O = Object(this);
    var len = O.length >>> 0;
    if (typeof callback !== 'function') {
      throw new TypeError(callback + ' is not a function');
    }
    if (arguments.length > 1) {
      T = arguments[1];
    }
    A = new Array(len);
    k = 0;
    while (k < len) {
      var kValue, mappedValue;
      if (k in O) {
        kValue = O[k];
        mappedValue = callback.call(T, kValue, k, O);
        A[k] = mappedValue;
      }
      k++;
    }
    return A;
  };
}