Skip to content

Instantly share code, notes, and snippets.

@yesasha
Last active May 16, 2018 11:17
Show Gist options
  • Save yesasha/6721ca673af935fa85a19ffef9d75250 to your computer and use it in GitHub Desktop.
Save yesasha/6721ca673af935fa85a19ffef9d75250 to your computer and use it in GitHub Desktop.
List of usable functions. Use it as a reference only. Don't plug it as a library.
//////////////// IS //////////////////
// Check if an object is primitive
function isPrimitive (obj) {
var type = typeof obj;
return obj == null || type === 'boolean' || type === 'number' || type === 'string' || type === 'symbol';
}
// Check if an object is primitive
function isPrimitive2 (obj) {
return obj == null || typeof obj !== 'object';
}
// Check if an object is primitive or a wrapped primitive
function isPrimitive3 (obj) {
var type = Object.prototype.toString.call(obj).slice(8, -1);
return obj == null || type === 'Boolean' || type === 'Number' || type === 'String' || type === 'Symbol';
}
function isNull (obj) {
return obj === null;
}
function isNull2 (obj) { // Overcomplexify
return Object.prototype.toString.call(obj) === '[object Null]';
}
// Primitive boolean only
function isBoolean (obj) { // Most simple
return obj === true || obj === false;
}
// Primitive boolean or boolean object
function isBoolean2 (obj) {
return Object.prototype.toString.call(obj) === '[object Boolean]';
}
// Primitive boolean only
function isBoolean3 (obj) {
return typeof obj === 'boolean';
}
// Boolean object only
function isBoolean4 (obj) {
return obj instanceof Boolean;
}
// Primitive boolean or boolean object
function isBoolean5 (obj) {
return typeof obj === 'boolean' || obj instanceof Boolean;
}
// Boolean object only
function isBoolean6 (obj) {
return Object.prototype.toString.call(obj) === '[object Boolean]' && typeof obj !== 'boolean';
}
function isUndefined (obj) {
return obj === void(0);
}
function isUndefined2 (obj) {
return typeof obj === 'undefined';
}
function isUndefined3 (obj) { // Overcomplexify
return Object.prototype.toString.call(obj) === '[object Undefined]';
}
function isNullOrUndefined (obj) {
return obj == null;
}
// Primitive number or number object
function isNumber (obj) {
return Object.prototype.toString.call(obj) === '[object Number]';
}
// Number object only
function isNumber2 (obj) {
return obj instanceof Number;
}
// Primitive number only
function isNumber3 (obj) {
return typeof obj === 'number';
}
// Primitive number or number object
function isNumber4 (obj) {
return typeof obj === 'number' || obj instanceof Number;
}
// Number object only
function isNumber5 (obj) {
return Object.prototype.toString.call(obj) === '[object Number]' && typeof obj !== 'number';
}
// Primitive string or string object
function isString (obj) {
return Object.prototype.toString.call(obj) === '[object String]';
}
// String object only
function isString2 (obj) {
return obj instanceof String;
}
// Primitive string only
function isString3 (obj) {
return typeof obj === 'string';
}
// Primitive string or string object
function isString4 (obj) {
return typeof obj === 'string' || obj instanceof String;
}
// String object only
function isString5 (obj) {
return Object.prototype.toString.call(obj) === '[object String]' && typeof obj !== 'string';
}
function isSymbol (obj) {
return typeof obj === 'symbol';
}
function isSymbol2 (obj) { // Overcomplexify
return Object.prototype.toString.call(obj) === '[object Symbol]';
}
// https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN
function isNaN2 (obj) {
return typeof obj === 'number' && isNaN(obj);
}
// Supports Number objects
function isNaN3 (obj) {
return Object.prototype.toString.call(obj) === '[object Number]' && isNaN(obj);
}
function isArray (obj) {
return Array.isArray(obj);
}
function isArray2 (obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
function isArray3 (obj) {
return obj instanceof Array;
}
function isArrayLike (obj) {
if (Array.isArray(obj)) {
return true;
}
if (obj == null) {
return false;
}
var type = Object.prototype.toString.call(obj);
if (type === '[object Window]') {
return false;
}
if (type === '[object Function]') {
return false;
}
if (typeof obj.length !== 'number') {
return false;
}
if (obj.length < 0) {
return false;
}
return true;
}
function isObject (obj) {
return Object.prototype.toString.call(obj) === '[object Object]';
}
function isObject2 (obj) {
return obj instanceof Object;
}
function isPlainObject (obj) {
// Detect obvious negatives
if (obj == null || Object.prototype.toString.call(obj) !== '[object Object]') {
return false;
}
var proto = Object.getPrototypeOf(obj);
// Objects with no prototype (e.g., `Object.create( null )`) are plain
// Objects with prototype are plain iff they were constructed by a global Object function
return proto === null || Object.prototype.hasOwnProperty.call(proto, 'constructor') && proto.constructor === Object;
}
function isHostObject (obj) {
if (obj == null) {
return false;
}
var type = Object.prototype.toString.call(obj).slice(8, -1);
return type !== 'Boolean' && type !== 'Number' && type !== 'String' && type !== 'Symbol' && type !== 'Object' && type !== 'Function';
}
function isUserConstructedObject (obj) {
// Detect obvious negatives
if (obj == null || Object.prototype.toString.call(obj) !== '[object Object]') {
return false;
}
var proto = Object.getPrototypeOf(obj);
// Objects with no prototype (e.g., `Object.create( null )`) are not constructed by user constructor
// Objects with prototype are user constructed iff they were not constructed by a global Object function
return proto !== null && proto.constructor !== Object;
}
// From jQuery
function isFunction (obj) {
// Support: Chrome <=57, Firefox <=52
// In some browsers, typeof returns "function" for HTML <object> elements
// (i.e., `typeof document.createElement( "object" ) === "function"`).
// We don't want to classify *any* DOM node as a function.
return typeof obj === 'function' && typeof obj.nodeType !== 'number';
}
function isFunction2 (obj) {
return Object.prototype.toString.call(obj) === '[object Function]';
}
function isFunction3 (obj) {
return obj instanceof Function;
}
function isDate (obj) {
return Object.prototype.toString.call(obj) === '[object Date]';
}
function isDate2 (obj) {
return obj instanceof Date;
}
function isRegExp (obj) {
return Object.prototype.toString.call(obj) === '[object RegExp]';
}
function isRegExp2 (obj) {
return obj instanceof RegExp;
}
function isError (obj) {
return Object.prototype.toString.call(obj) === '[object Error]';
}
function isError2 (obj) {
return obj instanceof Error;
}
function isError3 (obj) {
return obj.name === 'Error';
}
function isEvalError (obj) {
return obj instanceof EvalError;
}
function isEvalError (obj) {
return obj.name === 'EvalError';
}
function isInternalError (obj) {
return obj instanceof InternalError;
}
function isInternalError (obj) {
return obj.name === 'InternalError';
}
function isRangeError (obj) {
return obj instanceof RangeError;
}
function isRangeError (obj) {
return obj.name === 'RangeError';
}
function isReferenceError (obj) {
return obj instanceof ReferenceError;
}
function isReferenceError (obj) {
return obj.name === 'ReferenceError';
}
function isSyntaxError (obj) {
return obj instanceof SyntaxError;
}
function isSyntaxError (obj) {
return obj.name === 'SyntaxError';
}
function isTypeError (obj) {
return obj instanceof TypeError;
}
function isTypeError (obj) {
return obj.name === 'TypeError';
}
function isURIError (obj) {
return obj instanceof URIError;
}
function isURIError (obj) {
return obj.name === 'URIError';
}
function isArguments (obj) {
return Object.prototype.toString.call(obj) === '[object Arguments]';
}
function isNumeric (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function isNumeric2 (n) {
return isFinite(parseFloat(n));
}
function isNumeric3 (n) {
return !isNaN(parseFloat(n));
}
function isNumeric4 (n) {
var type = typeof n;
return (type === 'number' || type === 'string') && !isNaN(n - parseFloat(n));
}
function isNumeric5 (n) {
var type = typeof n;
return (type === 'number' || type === 'string') && !isNaN(parseFloat(n)) && isFinite(n);
}
function isNumeric6 (n) {
var type = typeof n;
return (type === 'number' || type === 'string') && isFinite(parseFloat(n));
}
function isNumeric7 (n) {
var type = typeof n;
return (type === 'number' || type === 'string') && !isNaN(parseFloat(n));
}
function isNumeric8 (n) {
var type = Object.prototype.toString.call(n);
return (type === '[object Number]' || type === '[object String]') && !isNaN(n - parseFloat(n));
}
function isNumeric9 (n) {
var type = Object.prototype.toString.call(n);
return (type === '[object Number]' || type === '[object String]') && !isNaN(parseFloat(n)) && isFinite(n);
}
function isNumeric10 (n) {
var type = Object.prototype.toString.call(n);
return (type === '[object Number]' || type === '[object String]') && isFinite(parseFloat(n));
}
function isNumeric11 (n) {
var type = Object.prototype.toString.call(n);
return (type === '[object Number]' || type === '[object String]') && !isNaN(parseFloat(n));
}
function isBlob (obj) {
return Object.prototype.toString.call(obj) === '[object Blob]';
}
function isBlob2 (obj) {
return obj instanceof Blob;
}
function isFile (obj) {
return Object.prototype.toString.call(obj) === '[object File]';
}
function isFile2 (obj) {
return obj instanceof File;
}
function isFileList (obj) {
return Object.prototype.toString.call(obj) === '[object FileList]';
}
function isFileList2 (obj) {
return obj instanceof FileList;
}
function isWindow (obj) {
return Object.prototype.toString.call(obj) === '[object Window]';
}
// From jQuery
function isWindow2 (obj) {
return obj != null && obj === obj.window;
}
function isHTMLElement (obj) {
return Object.prototype.toString.call(obj).match(/HTML.+Element/) !== null;
}
function isHTMLElement2 (obj) {
return obj instanceof HTMLElement;
}
function isHTMLElement3 (obj) {
return obj != null && obj.nodeType === 1;
}
function isNode (obj) {
return obj != null && typeof obj.nodeType === 'number';
}
function isNode2 (obj) {
var type = Object.prototype.toString.call(obj).slice(8, -1);
return (
type.match(/HTML.+Element/) !== null ||
type === 'Text' ||
type === 'ProcessingInstruction' ||
type === 'Comment' ||
type === 'HTMLDocument' ||
type === 'DocumentType' ||
type === 'DocumentFragment'
);
}
function isNodeNotHTMLElement (obj) {
return obj != null && typeof obj.nodeType === 'number' && obj.nodeType !== 1;
}
function isNodeNotHTMLElement2 (obj) {
var type = Object.prototype.toString.call(obj).slice(8, -1);
return (
type === 'Text' ||
type === 'ProcessingInstruction' ||
type === 'Comment' ||
type === 'HTMLDocument' ||
type === 'DocumentType' ||
type === 'DocumentFragment'
);
}
function isHTMLHtmlElement (obj) {
return Object.prototype.toString.call(obj) === '[object HTMLHtmlElement]';
}
function isText (obj) {
return Object.prototype.toString.call(obj) === '[object Text]';
}
function isText2 (obj) {
return obj != null && obj.nodeType === 3;
}
function isProcessingInstruction () {
return Object.prototype.toString.call(obj) === '[object ProcessingInstruction]';
}
function isProcessingInstruction2 () {
return obj != null && obj.nodeType === 7;
}
function isComment (obj) {
return Object.prototype.toString.call(obj) === '[object Comment]';
}
function isComment2 (obj) {
return obj != null && obj.nodeType === 8;
}
function isHTMLDocument (obj) {
return Object.prototype.toString.call(obj) === '[object HTMLDocument]';
}
function isHTMLDocument2 (obj) {
return obj != null && obj.nodeType === 9;
}
function isDocumentType () {
return Object.prototype.toString.call(obj) === '[object DocumentType]';
}
function isDocumentType2 () {
return obj != null && obj.nodeType === 10;
}
function isDocumentFragment () {
return Object.prototype.toString.call(obj) === '[object DocumentFragment]';
}
function isDocumentFragment2 () {
return obj != null && obj.nodeType === 11;
}
function isHTMLCollection (obj) {
return Object.prototype.toString.call(obj) === '[object HTMLCollection]';
}
function isHTMLCollection2 (obj) {
return obj instanceof HTMLCollection;
}
function isNodeList (obj) {
return Object.prototype.toString.call(obj) === '[object NodeList]';
}
function isNodeList2 (obj) {
return obj instanceof NodeList;
}
// https://stackoverflow.com/questions/28163033/when-is-nodelist-live-and-when-is-it-static
function isLiveCollection (collection) {
if (collection.length < 1) {
return void(0); //inconclusivw
}
var body = document.getElementsByTagName('body')[0];
var l1 = collection.length;
var clone = collection.item(0).cloneNode();
clone.style.display = 'none';
body.appendChild(clone);
var l2 = collection.length;
body.removeChild(clone);
return l2 !== l1;
}
/** https://developer.mozilla.org/ru/docs/Web/API/DOMTokenList
* Such a set is returned by
* Element.classList,
* HTMLLinkElement.relList,
* HTMLAnchorElement.relList,
* HTMLAreaElement.relList,
* HTMLIframeElement.sandbox,
* HTMLOutputElement.htmlFor.
*/
function isDOMTokenList (obj) {
return Object.prototype.toString.call(obj) === '[object DOMTokenList]';
}
function isDOMTokenList2 (obj) {
return obj instanceof DOMTokenList;
}
// https://developer.mozilla.org/en-US/docs/Web/API/NamedNodeMap
function isNamedNodeMap (obj) {
return Object.prototype.toString.call(obj) === '[object NamedNodeMap]';
}
function isNamedNodeMap2 (obj) {
return obj instanceof NamedNodeMap;
}
function isDOMStringMap (obj) {
return Object.prototype.toString.call(obj) === '[object DOMStringMap]';
}
function isDOMStringMap2 (obj) {
return obj instanceof DOMStringMap;
}
// Element.getAttributeNode()
// Element.attributes[i]
function isAttr (obj) {
return Object.prototype.toString.call(obj) === '[object Attr]';
}
function isAttr2 (obj) {
return obj instanceof Attr;
}
function isCSSStyleDeclaration (obj) {
return Object.prototype.toString.call(obj) === '[object CSSStyleDeclaration]';
}
function isCSSStyleDeclaration2 (obj) {
return obj instanceof isCSSStyleDeclaration;
}
function isStyleSheetList (obj) {
return Object.prototype.toString.call(obj) === '[object StyleSheetList]';
}
function isStyleSheetList2 (obj) {
return obj instanceof StyleSheetList;
}
function isCSSStyleSheet (obj) {
return Object.prototype.toString.call(obj) === '[object CSSStyleSheet]';
}
function isCSSStyleSheet2 (obj) {
return obj instanceof CSSStyleSheet;
}
function isCSSRuleList (obj) {
return Object.prototype.toString.call(obj) === '[object CSSRuleList]';
}
function isCSSRuleList2 (obj) {
return obj instanceof CSSRuleList;
}
function isCSSStyleRule (obj) {
return Object.prototype.toString.call(obj) === '[object CSSStyleRule]';
}
function isCSSStyleRule2 (obj) {
return obj instanceof CSSStyleRule;
}
function isTypedArray (obj) {
return (
obj instanceof Int8Array ||
obj instanceof Uint8Array ||
obj instanceof Uint8ClampedArray ||
obj instanceof Int16Array ||
obj instanceof Uint16Array ||
obj instanceof Int32Array ||
obj instanceof Uint32Array ||
obj instanceof Float32Array ||
obj instanceof Float64Array
)
}
function isTypedArray2 (obj) {
var type = Object.prototype.toString.call(obj).slice(8, -1);
return (
type === 'Int8Array' ||
type === 'Uint8Array' ||
type === 'Uint8ClampedArray' ||
type === 'Int16Array' ||
type === 'Uint16Array' ||
type === 'Int32Array' ||
type === 'Uint32Array' ||
type === 'Float32Array' ||
type === 'Float64Array'
)
}
function isTypedArray3 (obj) {
return Object.prototype.toString.call(obj).match(/\[object .+Array]/) !== null;
}
function isInt8Array (obj) {
return Object.prototype.toString.call(obj) === '[object Int8Array]';
}
function isInt8Array2 (obj) {
return obj instanceof Int8Array;
}
function isUint8Array (obj) {
return Object.prototype.toString.call(obj) === '[object Uint8Array]';
}
function isUint8Array2 (obj) {
return obj instanceof Uint8Array;
}
function isUint8ClampedArray (obj) {
return Object.prototype.toString.call(obj) === '[object Uint8ClampedArray]';
}
function isUint8ClampedArray2 (obj) {
return obj instanceof Uint8ClampedArray;
}
function isInt16Array (obj) {
return Object.prototype.toString.call(obj) === '[object Int16Array]';
}
function isInt16Array2 (obj) {
return obj instanceof Int16Array;
}
function isUint16Array (obj) {
return Object.prototype.toString.call(obj) === '[object Uint16Array]';
}
function isUint16Array2 (obj) {
return obj instanceof Uint16Array;
}
function isInt32Array (obj) {
return Object.prototype.toString.call(obj) === '[object Int32Array]';
}
function isInt32Array2 (obj) {
return obj instanceof Int32Array;
}
function isUint32Array (obj) {
return Object.prototype.toString.call(obj) === '[object Uint32Array]';
}
function isUint32Array2 (obj) {
return obj instanceof Uint32Array;
}
function isFloat32Array (obj) {
return Object.prototype.toString.call(obj) === '[object Float32Array]';
}
function isFloat32Array2 (obj) {
return obj instanceof Float32Array;
}
function isFloat64Array (obj) {
return Object.prototype.toString.call(obj) === '[object Float64Array]';
}
function isFloat64Array2 (obj) {
return obj instanceof Float64Array;
}
function isArrayBuffer (obj) {
return Object.prototype.toString.call(obj) === '[object ArrayBuffer]';
}
function isArrayBuffer2 (obj) {
return obj instanceof ArrayBuffer;
}
function isDataView (obj) {
return Object.prototype.toString.call(obj) === '[object DataView]';
}
function isDataView2 (obj) {
return obj instanceof DataView;
}
function isImageData (obj) {
return Object.prototype.toString.call(obj) === '[object ImageData]';
}
function isMap (obj) {
return Object.prototype.toString.call(obj) === '[object Map]';
}
function isWeakMap (obj) {
return Object.prototype.toString.call(obj) === '[object WeakMap]';
}
function isSet (obj) {
return Object.prototype.toString.call(obj) === '[object Set]';
}
function isWeakSet (obj) {
return Object.prototype.toString.call(obj) === '[object WeakSet]';
}
function isBuffer (obj) {
if (typeof Buffer === 'function' && typeof Buffer.isBuffer === 'function') {
return Buffer.isBuffer(obj);
} else {
return false;
}
}
//////////////////////// CLONE ///////////
function cloneRegExp (obj) {
return new RegExp(obj);
}
function cloneRegExp2 (obj) {
return new RegExp(obj.source, obj.flags);
}
function cloneDate (obj) {
return new Date(obj.getTime());
}
function cloneArguments (obj) {
return (function () {return arguments}).apply(null, Array.prototype.slice.call(obj));
}
function cloneArrayBuffer (obj) {
return obj.slice(0);
}
function cloneArrayBuffer2 (obj) {
var aB = new ArrayBuffer(obj.byteLength);
new Uint8Array(dst).set(new Uint8Array(obj));
return aB;
}
function cloneArrayBuffer3 (obj) {
return (new Uint8Array(new Uint8Array(obj))).buffer;
}
function cloneArrayBuffer4 (obj) {
return (Uint8Array.from(new Uint8Array(obj))).buffer;
}
function cloneArrayBuffer5 (obj) {
var tA = new Uint8Array(obj.byteLength);
tA.set(new Uint8Array(obj));
return tA.buffer;
}
function cloneTypedArray (obj) {
return obj.slice(0); // Don't need a zero..?
}
function cloneTypedArray2 (obj) {
return new obj.constructor(obj);
}
function cloneTypedArray3 (obj) {
return obj.constructor.from(obj);
}
function cloneTypedArray4 (obj) {
var tA = new obj.constructor(obj.length);
tA.set(obj);
return tA;
}
function cloneDataView (obj) {
return new DataView((new Uint8Array(new Uint8Array(obj.buffer))).buffer, obj.byteOffset, obj.byteLength);
}
function cloneError (obj) {
return new window[obj.name](obj.message, obj.fileName, obj.lineNumber);
}
function cloneImageData (obj) {
return document.createElement('canvas').getContext('2d').createImageData(obj);
}
function cloneBlob (obj) {
return obj.slice(0, obj.size, obj.type); // !
}
function cloneBlob2 (obj) {
return new Blob([obj], {type: obj.type});
}
// https://stackoverflow.com/questions/41008024/how-to-create-a-modified-copy-of-a-file-object-in-javascript
function cloneFile (obj) {
return new File([obj], obj.name, {type: obj.type});
}
function cloneFile2 (obj) {
var data = new FormData();
data.append('file', obj, obj.name);
return data.get('file');
}
function cloneSet (obj) {
var clonedSet = new Set();
obj.forEach(function (value1, value2, set) {
clonedSet.add(value1);
});
return clonedSet;
}
function cloneMap (obj) {
var clonedMap = new Map();
obj.forEach(function (value, key, map) {
clonedMap.set(key, value);
});
return clonedMap;
}
function cloneBuffer (obj) {
return Buffer.from(obj);
}
///////////////////////// GET /////////////////
//////////// Get ELEMENTS ////////////////////
function getElementById (id) {
return document.getElementById(id);
}
// In HTML5, the "name" attribute is deprecated and has been replaced by the "id" attribute for many elements.
function getElementsByName (name) {
return document.getElementsByName(name);
}
function querySelector (query, element) {
return (element || document).querySelector(query);
}
function querySelectorAll (query, element) {
return (element || document).querySelectorAll(query);
}
function getElementsByTagName (tagName, element) {
return (element || document).getElementsByTagName(tagName);
}
function getElementsByClassName (className, element) {
return (element || document).getElementsByClassName(className);
}
function createElement (tagName, options) {
return document.createElement(tagName, options);
}
function createTextNode (data) {
return document.createTextNode(data);
}
function createComment (data) {
return document.createComment(data);
}
function createDocumentFragment () {
return document.createDocumentFragment();
}
function createProcessingInstruction (target, data) {
return document.createProcessingInstruction(target, data);
}
function createDocumentType (qualifiedNameStr, publicId, systemId) {
return document.implementation.createDocumentType(qualifiedNameStr, publicId, systemId);
}
function createDocument (namespaceURI, qualifiedNameStr, documentType) {
return document.implementation.createDocument(namespaceURI, qualifiedNameStr, documentType);
}
function createHTMLDocument (title) {
return document.implementation.createHTMLDocument(title);
}
function appendChild (element, aChild) {
return element.appendChild(aChild);
}
function removeElement (element) {
return element.parentNode.removeChild(element);
}
function removeElement2 (element) {
element.outerHTML = '';
return element; // An old element removed from DOM, but still exists
}
function insertBefore (newElement, referenceElement) {
return referenceElement.parentNode.insertBefore(newElement, referenceElement);
}
function insertAfter (newElement, referenceElement) {
return referenceElement.parentNode.insertBefore(newElement, referenceElement.nextSibling);
}
function prependChild (element, aChild) {
return element.insertBefore(aChild, element.firstChild);
}
function cloneNode (node, deep) {
return node.cloneNode(deep || false);
}
function importNode (externalNode, deep) {
return document.importNode(externalNode, deep || false);
}
function cloneNode2 (externalNode, deep) {
return node.ownerDocument.importNode(externalNode, deep || false);
}
function adoptNode (externalNode) {
return document.adoptNode(externalNode);
}
function replaceElement (newElement, oldElement) {
return oldElement.parentNode.replaceChild(newElement, oldElement);
}
function replaceElement2 (newElement, oldElement) {
oldElement.outerHTML = newElement.outerHTML;
return oldElement; // An old element removed from DOM, but still exists
}
function appendHTML (element, text) {
element.insertAdjacentHTML('beforeend', text);
}
function prependHTML (element, text) {
element.insertAdjacentHTML('afterbegin', text);
}
function beforeHTML (element, text) {
element.insertAdjacentHTML('beforebegin', text);
}
function afterHTML (element, text) {
element.insertAdjacentHTML('afterend', text);
}
function appendText (element, text) {
element.insertAdjacentText('beforeend', text);
}
function prependText (element, text) {
element.insertAdjacentText('afterbegin', text);
}
function beforeText (element, text) {
element.insertAdjacentText('beforebegin', text);
}
function afterText (element, text) {
element.insertAdjacentText('afterend', text);
}
function appendElement (targetElement, element) {
return targetElement.insertAdjacentElement('beforeend', element);
}
function prependElement (targetElement, element) {
return targetElement.insertAdjacentElement('afterbegin', element);
}
function beforeElement (targetElement, element) {
return targetElement.insertAdjacentElement('beforebegin', element);
}
function afterElement (targetElement, element) {
return targetElement.insertAdjacentElement('afterend', element);
}
function append (ChildNode) {
ChildNode.append.apply(ChildNode, Array.prototype.slice.call(arguments, 1));
}
function prepend (ChildNode) {
ChildNode.prepend.apply(ChildNode, Array.prototype.slice.call(arguments, 1));
}
function before (ChildNode) {
ChildNode.before.apply(ChildNode, Array.prototype.slice.call(arguments, 1));
}
function after (ChildNode) {
ChildNode.after.apply(ChildNode, Array.prototype.slice.call(arguments, 1));
}
function replaceWith (ChildNode) {
ChildNode.replaceWith.apply(ChildNode, Array.prototype.slice.call(arguments, 1));
}
function createAttribute (name, value) {
var node = document.createAttribute(name);
node.value = value;
return node;
}
function cloneAttribute (obj) {
var node = document.createAttribute(obj.name);
node.value = obj.value;
return node;
}
function setAttribute (element, name, value) {
element.setAttribute(name, value);
}
function setAttribute2 (element, name, value) {
var node = document.createAttribute(name);
node.value = value;
return element.attributes.setNamedItem(node);
}
function setAttribute3 (element, name, value) {
var node = document.createAttribute(name);
node.value = value;
return element.setAttributeNode(node);
}
function getAttribute (element, name) {
return element.getAttribute(name);
}
function getAttribute2 (element, name) {
return element.hasAttribute(name) ? element.getAttribute(name) : null;
}
function getAttribute3 (element, name) {
return element.getAttributeNode(name).value;
}
function getAttribute4 (element, name) {
return (element.hasAttribute(name)) ? null : element.getAttributeNode(name).value;
}
function getAttribute5 (element, name) {
return element.attributes.getNamedItem(name).value;
}
function getAttribute6 (element, name) {
var attr = element.attributes.getNamedItem(name);
return (attr === null) ? null : attr.value;
}
function removeAttribute (element, name) {
element.removeAttribute(name);
}
function removeAttribute2 (element, name) {
return element.attributes.removeNamedItem(name);
}
function hasAttribute (element, name) {
return element.hasAttribute(name);
}
function hasAttribute2 (element, name) {
return element.attributes.getNamedItem(name) !== null;
}
function getAttributeNode (element, name) {
return element.getAttributeNode(name);
}
function getAttributeNode2 (element, name) {
return element.attributes.getNamedItem(name);
}
function setAttributeNode (element, node) {
return element.setAttributeNode(node);
}
function setAttributeNode2 (element, node) {
return element.attributes.setNamedItem(node);
}
function removeAttributeNode (element, node) {
return element.removeAttributeNode(node);
}
/////////////// GET/SET HELPERS ///////////////////
function getAllPropertyNames (obj) {
var props = [];
if (obj != null) {
do {
props = props.concat(Object.getOwnPropertyNames(obj));
} while (obj = Object.getPrototypeOf(obj));
}
return props;
}
function getOwnPropertyNamesAndSymbols (obj) {
var keys = [];
if (obj != null) {
keys = keys.concat(Object.getOwnPropertyNames(obj));
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
if (getOwnPropertySymbols) {
keys = keys.concat(getOwnPropertySymbols(obj));
}
}
return keys;
}
function innerHTML (element, HTML) {
if ('1' in arguments) { // null clears value
var oldHTML = element.innerHTML;
element.innerHTML = HTML;
return oldHTML;
} else {
return element.innerHTML;
}
}
function outerHTML (element, HTML) {
if ('1' in arguments) { // null clears value
element.outerHTML = HTML;
return element; // An old element removed from DOM, but still exists
} else {
return element.outerHTML;
}
}
function textContent (element, text) {
if ('1' in arguments) { // null and undefined clears value
var oldText = element.textContent;
element.textContent = text;
return oldText;
} else {
return element.textContent;
}
}
//////////////// MISC //////////////////
var littleEndian = (function() {
var buffer = new ArrayBuffer(2);
new DataView(buffer).setInt16(0, 256, true /* littleEndian */);
// Int16Array uses the platform's endianness.
return new Int16Array(buffer)[0] === 256;
})();
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
function sign (x) {
x = +x; // To number
if (x === 0 || isNaN(x)) {
return x;
}
return x > 0 ? 1 : -1;
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc
function trunc (v) {
v = +v;
if (!isFinite(v)) return v;
return (v - v % 1) || (v < 0 ? -0 : v === 0 ? v : 0);
}
function trunc2 (v) {
v = +v;
return (v - v % 1) || (!isFinite(v) || v === 0 ? v : v < 0 ? -0 : 0);
}
function strongTrim (str) {
if (Object.prototype.toString.call(obj) !== '[object String]') return str;
str = str.replace(/\s+/g, ' ').replace(/(^ | $)/g, '');
return str;
}
function normalizeNewLines (string, how) {
string = string.replace(/\r\n|\r/g, '\n');
if (how != null) {
return string.replace(/\n/g, how);
}
return string;
}
function inArray (arr, val) {
if (arr == null) {
return false;
}
return !!~Array.prototype.indexOf.call(arr, val);
}
function inString (str, subStr) {
if (str == null) {
return false;
}
return !!~String.prototype.indexOf.call(str, subStr);
}
function stringToArray (str) {
return str.split('');
}
function stringToArray2 (str) {
return Array.prototype.slice.call(str);
}
// Does not work for non english
function tokenize (str) {
return str.match(/\w+/g);
}
// Works for all languages
function tokenize2 (str) {
return str.match(/\S+/g);
}
// https://jsperf.com/thor-indexof-vs-for/5
function indexOf (list, element, i) {
i = +i || 0;
var len = list.length;
for (; i < len; i++) {
if (list[i] === element) {
return i;
}
}
return -1;
}
function hasOwnProperty (obj, prop) {
if (obj == null) {
return false;
}
return Object.prototype.hasOwnProperty.call(obj, prop);
}
function hasProperty (obj, prop) {
if (obj == null) {
return false;
}
return prop in Object(obj); // !
}
// From jQuery
// Convert dashed to camelCase; used by the css and data modules
// Support: IE <=9 - 11, Edge 12 - 13
// Microsoft forgot to hump their vendor prefix (#9572)
function camelCase (string) {
return string.replace(/^-ms-/, 'ms-').replace(/-([a-z])/g, function(all, letter) {
return letter.toUpperCase();
});
}
function regExpSpecialChars (str) {
return str
.replace(/\\/g, '\\\\')
.replace(/\[/g, '\\[')
.replace(/\^/g, '\\^')
.replace(/\$/g, '\\$')
.replace(/\./g, '\\.')
.replace(/\|/g, '\\|')
.replace(/\?/g, '\\?')
.replace(/\*/g, '\\*')
.replace(/\+/g, '\\+')
.replace(/\(/g, '\\(')
.replace(/\)/g, '\\)');
}
function regExpSpecialChars2 (str) {
return str.replace(/[[\\^$.|?*+()]/g, function (matched) {
return '\\' + matched;
});
}
function regExpSpecialChars3 (str) {
return str.replace(/\[|\\|\^|\$|\.|\||\?|\*|\+|\(|\)/g, function (matched) {
return '\\' + matched;
});
}
function regExpSquareBracketsSpecialChars (str) {
return str
.replace(/\\/g, '\\\\')
.replace(/\^/g, '\\^')
.replace(/]/g, '\\]')
.replace(/-/g, '\\-');
}
function regExpSquareBracketsSpecialChars2 (str) {
return str.replace(/[-^\\\]]/g, function (matched) {
return '\\' + matched;
});
}
function regExpSquareBracketsSpecialChars3 (str) {
return str.replace(/-\^\\]/g, function (matched) {
return '\\' + matched;
});
}
// https://github.com/tjcafferkey/stringinject
// Fixed and simple version
function stringInject (str, data) {
return str.replace(/{.*?}/g, function(i) {
var key = i.replace('{', '').replace('}', '');
return Object.prototype.hasOwnProperty.call(data, key) ? data[key] : i;
});
}
// https://github.com/tjcafferkey/stringinject
// Fixed and simple version
function stringInject2 (str, data) {
return str.replace(/{[^}]*}/g, function(i) {
var key = i.replace('{', '').replace('}', '');
return Object.prototype.hasOwnProperty.call(data, key) ? data[key] : i;
});
}
// https://github.com/tjcafferkey/stringinject
// Fixed and simple version
function stringInject3 (str, data) {
return str.replace(/{[^{}]*}/g, function(i) {
var key = i.replace('{', '').replace('}', '');
return Object.prototype.hasOwnProperty.call(data, key) ? data[key] : i;
});
}
// https://github.com/tjcafferkey/stringinject
// Another version
function stringInject4 (str, mapObj){
var keys = Object.keys(mapObj);
for (var i = 0; i < keys.length; i++) {
keys[i] = '{' + keys[i]
.replace(/\\/g, '\\\\')
.replace(/\[/g, '\\[')
.replace(/\^/g, '\\^')
.replace(/\$/g, '\\$')
.replace(/\./g, '\\.')
.replace(/\|/g, '\\|')
.replace(/\?/g, '\\?')
.replace(/\*/g, '\\*')
.replace(/\+/g, '\\+')
.replace(/\(/g, '\\(')
.replace(/\)/g, '\\)') + '}';
}
return str.replace(new RegExp(keys.join('|'), 'g'), function (matched) {
return mapObj[matched.slice(1, -1)];
});
}
// https://stackoverflow.com/questions/15604140/replace-multiple-strings-with-multiple-other-strings
// Enhanced version
function replaceAll (str, mapObj){
var keys = Object.keys(mapObj);
for (var i = 0; i < keys.length; i++) {
keys[i] = keys[i]
.replace(/\\/g, '\\\\')
.replace(/\[/g, '\\[')
.replace(/\^/g, '\\^')
.replace(/\$/g, '\\$')
.replace(/\./g, '\\.')
.replace(/\|/g, '\\|')
.replace(/\?/g, '\\?')
.replace(/\*/g, '\\*')
.replace(/\+/g, '\\+')
.replace(/\(/g, '\\(')
.replace(/\)/g, '\\)');
}
return str.replace(new RegExp(keys.join('|'), 'g'), function (matched) {
return mapObj[matched];
});
}
function forEachNode (node, callback, thisArg) {
if (!node) {
return;
}
callback.call(thisArg, node);
var childNodes = node.childNodes || [];
for (var i = 0; i < childNodes.length; i++) {
forEachNode(childNodes[i], callback, thisArg);
}
}
function forEachNode2 (node, callback, thisArg) {
if (!node) {
return;
}
switch (node.nodeType) {
case Node.ELEMENT_NODE:
case Node.DOCUMENT_NODE:
case Node.DOCUMENT_FRAGMENT_NODE:
case Node.TEXT_NODE:
case Node.PROCESSING_INSTRUCTION_NODE:
case Node.COMMENT_NODE:
case Node.DOCUMENT_TYPE_NODE:
break;
default:
return;
}
callback.call(thisArg, node);
var childNodes = node.childNodes || [];
for (var i = 0; i < childNodes.length; i++) {
forEachNode2(childNodes[i], callback, thisArg);
}
}
function forEachNode3 (node, callback, thisArg) {
if (!node) {
return;
}
switch (node.nodeType) {
case Node.ELEMENT_NODE:
case Node.DOCUMENT_NODE:
case Node.DOCUMENT_FRAGMENT_NODE:
callback.call(thisArg, node);
break;
case Node.TEXT_NODE:
case Node.PROCESSING_INSTRUCTION_NODE:
case Node.COMMENT_NODE:
case Node.DOCUMENT_TYPE_NODE:
callback.call(thisArg, node);
return;
default:
return;
}
var childNodes = node.childNodes || [];
for (var i = 0; i < childNodes.length; i++) {
forEachNode3(childNodes[i], callback, thisArg);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment