javascript code snippets

Javascript fetch
fetch('https://api-xxx.com/endpoint', {
  method: 'POST',
 body: JSON.stringify({id: "200"})
}).then(response => {
  if(response.ok){
      return response.json();  
  }
    throw new Error('Request failed!');
}, networkError => {
  console.log(networkError.message);
}).then(jsonResponse => {
  console.log(jsonResponse);
})
Appu - JQuery Send On toggle button fix
function showRejectionModal() {
    var modalContainer = document.getElementById("rejectionModal")
    if (modalContainer) {
        modalContainer.classList.add("in")
        modalContainer.style.display = "block"
        modalContainer.querySelector(".modal-content").style.marginTop = "100px"
    }
    return false
}

function hideRejectionModal() {
    var modalContainer = document.getElementById("rejectionModal")
    if (modalContainer) {
        modalContainer.classList.remove("in")
        modalContainer.style.display = "none"
    }
}

function handleSendOnButtons() {
    var customSendOnButton = document.getElementById("hfSendOnBtn")
    var standardSendOnButton = document.querySelector(".workitem-footer button[data-am-smartuiaction='submit']")

    var dispositionEngineerElement = document.getElementById("$form.dispositionengineer.id");
    var workflowStep = document.getElementById("$params.taskid");
    
    //console.log(`Form disposition: ${"$form.dispositionengineer.id"}`)
    console.log(`Disposition engineer: ${dispositionEngineerElement}`)
    console.log(`Workflow Step: ${workflowStep}`)
    
    // Daniel: changing check to enter this logic (when no disposition is set, hide the appropriate button)
    if (dispositionEngineerElement.value === '') {
        console.log("Toggling view")
        console.log(dispositionEngineerElement)
        console.log("Value of the disposition engineering element: " + dispositionEngineerElement.value)
        
        // customSendOnButton.style.display = "none"
        standardSendOnButton.style.display = "none"
}
    else {
        standardSendOnButton.style.display = "inline-block"
    	/*
        if (dispositionEngineerElement.value == 'Reject') {
        //appu commented out as this is not a Reject per se
            //	customSendOnButton.style.display = "inline-block"
       		//	standardSendOnButton.style.display = "none"
    	}
    	else {
        	customSendOnButton.style.display = "none"
        	standardSendOnButton.style.display = "inline-block"
    	}
        */
    }
    

}

window.onload = function() {
    var customSendOnButton = document.getElementById("hfSendOnBtn")
    // appu commented out as this is not a Reject per se
    // customSendOnButton.parentNode.removeChild(customSendOnButton)
    // document.querySelector(".workitem-footer.cs-dialog.binf-modal-footer div").appendChild(customSendOnButton)
}
Javascript Code for Sorting array and finding Largest No. in Array
let arr = [1,25,51,36,45,13,101]
const sorted = arr.sort((a, b) => a - b);
const Largest = arr.sort((a, b) => a - b)[arr.length - 1];
console.log(sorted)
console.log(Largest)
UseState hook in react
import React,{useState} from 'react'
const App=()=>{
  const [num,setNum]=useState(0);

  const Incre=()=>{
    setNum(num+1)
    document.title=`the  button was clicked ${num+1} times`
  }

  return(
    <>
    <button onClick={Incre}>
      click me {num}
    </button>
   
    </>
  )
}
export default App
ytdownloader
/*! jQuery v3.4.1 | (c) JS Foundation and other contributors | jquery.org/license */
function parse_query_string(n) {
    for (var t, f, u = n.split("&"), i = {}, r = 0; r < u.length; r++)
        t = u[r].split("="),
        typeof i[t[0]] == "undefined" ? i[t[0]] = decodeURIComponent(t[1]) : typeof i[t[0]] == "string" ? (f = [i[t[0]], decodeURIComponent(t[1])],
        i[t[0]] = f) : i[t[0]].push(decodeURIComponent(t[1]));
    return i
}
function openNav() {
    $(".topnav").toggleClass("responsive")
}
function ksearchvideo() {
    var n = $("#s_input").val().trim();
    return n && $.ajax({
        type: "POST",
        url: k_url_search,
        data: {
            q: n,
            vt: k_page
        },
        beforeSend: function() {
            $("#loader-wrapper").css("display", "block");
            $("#search-form").css("display", "none");
            $("#search-result").empty()
        },
        success: function(n, t, i) {
            i.status != 200 && setTimeout(function() {
                window.location.reload()
            }, 3e3);
            n.status == "ok" ? (n.p === "search" ? renderListVideo(n.items) : n.p !== "convert" || n.mess ? n.p === "facebook" ? n.mess ? renderFail(n.mess) : (k_vdata = n,
            renderFacebook(n)) : n.mess && renderFail(n.mess) : (k__token = n.token,
            k_time = n.timeExpires,
            renderDetail(n)),
            $("#loader-wrapper").css("display", "none")) : setTimeout(function() {
                window.location.reload()
            }, 3e3)
        },
        error: function(n) {
            return n.status == 429 ? convertFailed(txt_error_429) : convertFailed(txt_error_404)
        }
    }),
    !1
}
function k_parseDuration(n) {
    var i;
    if (!n)
        return "";
    var r = []
      , t = 0
      , f = n.match(/(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)W)?(?:(\d*)D)?T(?:(\d*)H)?(?:(\d*)M)?(?:(\d*)S)?/i)
      , u = [{
        pos: 1,
        multiplier: 31536e3
    }, {
        pos: 2,
        multiplier: 2592e3
    }, {
        pos: 3,
        multiplier: 604800
    }, {
        pos: 4,
        multiplier: 86400
    }, {
        pos: 5,
        multiplier: 3600
    }, {
        pos: 6,
        multiplier: 60
    }, {
        pos: 7,
        multiplier: 1
    }];
    if (null === f)
        return "";
    for (i = 0; i < u.length; i++)
        void 0 !== f[u[i].pos] && (t += parseInt(f[u[i].pos]) * u[i].multiplier);
    return 3599 < t && (r.push(parseInt(t / 3600)),
    t %= 3600),
    r.push(("0" + parseInt(t / 60)).slice(-2)),
    r.push(("0" + t % 60).slice(-2)),
    r.join(":")
}
function matchYoutubeUrl(n) {
    var t = /^(?:https?:\/\/)?(?:m\.|www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
    return n.match(t) ? n.match(t)[1] : !1
}
function fancyTimeFormat(n) {
    var i = ~~(n / 3600)
      , r = ~~(n % 3600 / 60)
      , u = ~~n % 60
      , t = "";
    return i > 0 && (t += "" + i + ":" + (r < 10 ? "0" : "")),
    t += "" + r + ":" + (u < 10 ? "0" : ""),
    t + ("" + u)
}
function renderFail(n) {
    $("#loader-wrapper").css("display", "none");
    $("#search-form").css("display", "block");
    var t = '<div class="error"><p>' + n + "<\/p><\/div>";
    $("#search-result").html(t)
}
function renderListVideo(n) {
    var t, i, r, u;
    if (n.length) {
        for (i = $("<ul>", {
            "class": "listvideo"
        }),
        t = 0; t < n.length; ++t)
            item = n[t],
            r = c_url_tmp + yt_tmp + item.v,
            u = '<li> <a  href="' + r + '" title="' + item.t + '" target="_blank"><div class="img-thumb"><img src="https://i.ytimg.com/vi/' + item.v + '/mqdefault.jpg" width="100%" height="100%"  alt="yt5s youtube downloader"/><span class="time">' + item.d + '<\/span><\/div> <div class="content"><div class="clearfix"><h3>' + item.t + "<\/h3><\/div><\/div><\/a><\/li>",
            i.append(u);
        $("#search-result").html(i)
    }
}
function convertSuccess(n) {
    $("#mesg-convert").addClass("hidden");
    $("#asuccess").attr("href", n).removeClass("hidden");
    $("#cnext").removeClass("hidden")
}
function convertFailed(n) {
    renderFail(n)
}
function checkTask(n) {
    $.ajax({
        type: "POST",
        url: k_url_check_task,
        data: {
            vid: $("#video_id").val(),
            b_id: n
        },
        success: function(t, i, r) {
            r.status != 200 ? checkTask(n) : t.c_status == "CONVERTED" ? convertSuccess(t.dlink) : t.c_status == "FAILED" ? convertFailed(t.mess) : setTimeout(function() {
                checkTask(n)
            }, 5e3)
        },
        error: function() {
            checkTask(n)
        }
    })
}
function convertFile(n) {
    var n = $("#formatSelect").find(":selected")
      , t = n.data("format")
      , i = n.val();
    $.ajax({
        type: "POST",
        url: k_url_convert,
        headers: {
            "X-Requested-Key": "de0cfuirtgf67a"
        },
        data: {
            v_id: $("#video_id").val(),
            ftype: t,
            fquality: i,
            token: k__token,
            timeExpire: k_time,
            client: k_prefix_name
        },
        beforeSend: function() {
            $("#formatSelect").addClass("hidden");
            $("#btn-action").addClass("hidden");
            $("#mesg-convert").removeClass("hidden")
        },
        success: function(n) {
            if (typeof n.c_status == "undefined")
                return convertFailed(txt_error_404);
            if (n.c_status == "ok" && typeof n.c_server != "undefined")
                convert_Server(n.c_server, t, i);
            else
                return n.c_status == "ok" && typeof n.d_url != "undefined" ? typeof n.checkLink != "undefined" ? getLink_Server(n.d_url) : convertSuccess(n.d_url) : convertFailed(txt_error_404)
        },
        error: function() {
            return convertFailed(txt_error_500)
        }
    })
}
function getLink_Server(n) {
    $.ajax({
        type: "GET",
        url: n,
        success: function(n) {
            if (typeof n.c_status == "undefined")
                return convertFailed(txt_error_404);
            if (n.c_status == "ok")
                convertSuccess(n.link);
            else
                return convertFailed(txt_error_404)
        },
        error: function() {
            return convertFailed(txt_error_500)
        }
    })
}
function convert_Server(n, t, i) {
    $.ajax({
        type: "POST",
        url: n + "/api/json/convert",
        data: {
            v_id: $("#video_id").val(),
            ftype: t,
            fquality: i,
            fname: $("#video_fn").val(),
            token: $("#c_token").val(),
            timeExpire: $("#c_time").val()
        },
        success: function(t) {
            return typeof t.status == "undefined" ? convertFailed(txt_error_404) : t.status == "success" ? t.statusCode == 200 ? convertSuccess(t.result) : t.statusCode == 300 && typeof t.jobId != "undefined" ? WSCheckStatus(n, t.jobId) : convertFailed(getStatusText(t.statusCode)) : convertFailed(txt_error_404)
        },
        error: function() {
            return convertFailed(txt_error_500)
        }
    })
}
function WSCheckStatus(n, t) {
    const i = new URL(n);
    var r = i.protocol == "https:" ? "wss:" : "ws:"
      , u = r + "//" + i.host + "/sub/" + t + "?fname=" + k_prefix_name;
    socket = new WebSocket(u);
    socket.onmessage = function(n) {
        var t = JSON.parse(n.data);
        t.action == "success" && convertSuccess(t.url);
        t.action == "progress" ? UpdateProgress(t.value) : t.action == "error" && convertFailed(txt_error_500)
    }
    ;
    socket.onerror = function() {
        convertFailed(txt_error_404)
    }
}
function UpdateProgress(n) {
    var t = $("#mesg-convert span");
    t.removeClass("lds-dual-ring");
    t.text(n + "%")
}
function getStatusText(n) {
    var t = "";
    return n == 500 ? t = txt_error_500 : n == 400 ? t = txt_error_404 : n == 300 && (t = txt_convert_next),
    t
}
function randomIntFromInterval(n, t) {
    return Math.floor(Math.random() * (t - n + 1) + n)
}
function renderDetail(n) {
    var t = '<div class="detail"><div class="thumbnail"><input type="hidden" id="video_id" value="' + n.vid + '" /><input type="hidden" id="video_fn" value="' + escapeHtml(n.fn) + '" /><input type="hidden" id="c_token" value="' + n.token + '" /><input type="hidden" id="c_time" value="' + n.timeExpires + '" />\n<img src="https://i.ytimg.com/vi/' + n.vid + '/0.jpg">\n<div class="content"><div class="clearfix">\n<h3>' + n.title + "<\/h3>\n<p>" + n.a + '<\/p>\n<p class="mag0">' + fancyTimeFormat(n.t) + "<\/p>";
    t += '<div class="magT10"> <div class="flex">';
    n.links != undefined && n.links != null ? (t += renderSelectQuality(n.links),
    t += '<button id="btn-action" class="btn-blue-small form-control" type="button" onclick="convertFile(0)">Get link<\/button>') : t += '<div class="error"><p>The live video cannot be processed. Please try again later.<\/p><\/div>';
    t += '<span id="mesg-convert" class="form-control mesg-convert hidden"> <span class="lds-dual-ring"><\/span> ' + txt_processing + '<\/span><a id="asuccess" class="form-control mesg-convert success hidden" rel="nofollow" href="#"> ' + txt_download + ' <\/a> &nbsp &nbsp<a id="cnext" class="form-control mesg-convert hidden" href="' + k_url_next + '">' + txt_convert_next + '<\/a><\/div><br/><br/><br/> <div class="addthis_inline_share_toolbox"><\/div> <\/div><\/div><\/div><\/div> ';
    $("#search-result").html(t);
    n.kc != undefined && n.kc != null && convertFile(n.kc)
}
function escapeHtml(n) {
    "use strict";
    return n.replace(/[\"&'\/<>]/g, function(n) {
        return {
            "'": "&#39;",
            "/": "&#47;",
            '"': "&quot;",
            "&": "&amp;",
            "<": "&lt;",
            ">": "&gt;"
        }[n]
    })
}
function KHtmlEncode(n) {
    var t = document.createElement("div");
    return t.innerText = t.textContent = n,
    t.innerHTML
}
function selectFileQuality(n) {
    if (k_vdata.links != undefined && k_vdata.links != null && k_vdata.links.hasOwnProperty(n)) {
        var t = k_vdata.title;
        $("#asuccess").attr("href", k_vdata.links[n]);
        $("#asuccess").attr("download", t + "_" + n + ".mp4")
    }
}
function renderFacebook(n) {
    var t;
    if (n.thumbnail = n.thumbnail ? n.thumbnail : "https://i.ytimg.com/vi/1/0.jpg",
    t = '<div class="detail"><div class="thumbnail">\n<img src="' + n.thumbnail + '">\n<div class="content"><div class="clearfix">\n<h3>' + n.title + '<\/h3>\n<p class="mag0">' + n.duration + "<\/p>",
    t += '<div class="magT10"> <div class="flex">',
    n.links != undefined && n.links != null) {
        t += '<select name="formatSelect" class="form-control form-control-small" id="formatSelect">';
        var r = ""
          , i = !1
          , u = n.title;
        n.links.hd != undefined && n.links.hd != null && (r += '<option value="hd" onclick="selectFileQuality(\'hd\')" >MP4 HD<\/option>',
        i || (i = n.links.hd,
        u += "_hd.mp4"));
        n.links.sd != undefined && n.links.sd != null && (r += '<option value="sd" onclick="selectFileQuality(\'sd\')" >MP4 SD<\/option>',
        i || (i = n.links.sd,
        u += "_sd.mp4"));
        n.links.audio != undefined && n.links.audio != null && (r += '<option value="audio" onclick="selectFileQuality(\'audio\')" >MP3<\/option>',
        i || (i = n.links.audio,
        u += "_audio.mp4"));
        t += r + "<\/select>";
        t += '<a id="asuccess" class="form-control mesg-convert success" target="_blank" rel="nofollow" href="' + i + '" download="' + u + '" data-type="mp4">' + txt_download + "<\/a>"
    }
    t += '<\/div><br/><br/><br/> <div class="addthis_inline_share_toolbox"><\/div> <\/div><\/div><\/div><\/div> ';
    $("#search-result").html(t);
    $("#formatSelect").change(function() {
        selectFileQuality(this.value)
    })
}
function renderSelectQuality(n) {
    var t = '<select class="form-control form-control-small" id="formatSelect">';
    return $.each({
        mp4: ["1080", "720", "480", "360", "240", "144"],
        "3gp": ["144"],
        ogg: ["128kbps"],
        mp3: ["320kbps", "256kbps", "192kbps", "128kbps", "64kbps"]
    }, function(i, r) {
        n[i] !== undefined && (t += '<optgroup label="' + i + '">',
        $.each(r, function(r, u) {
            $.each(n[i], function(n, i) {
                u == i.key && (t += '<option data-format="' + i.f + '" value="' + i.k + '" ' + (typeof i.selected != "undefined" && i.selected == "selected" ? "selected" : "") + ">" + i.q + " (" + i.size + ") <\/option>")
            })
        }),
        t += "<\/optgroup>")
    }),
    t += "<\/select>"
}
!function(n, t) {
    "use strict";
    "object" == typeof module && "object" == typeof module.exports ? module.exports = n.document ? t(n, !0) : function(n) {
        if (!n.document)
            throw new Error("jQuery requires a window with a document");
        return t(n)
    }
    : t(n)
}("undefined" != typeof window ? window : this, function(n, t) {
    "use strict";
    function br(n, t, i) {
        var r, e, u = (i = i || f).createElement("script");
        if (u.text = n,
        t)
            for (r in ee)
                (e = t[r] || t.getAttribute && t.getAttribute(r)) && u.setAttribute(r, e);
        i.head.appendChild(u).parentNode.removeChild(u)
    }
    function it(n) {
        return null == n ? n + "" : "object" == typeof n || "function" == typeof n ? ri[pr.call(n)] || "object" : typeof n
    }
    function pi(n) {
        var t = !!n && "length"in n && n.length
          , i = it(n);
        return !u(n) && !tt(n) && ("array" === i || 0 === t || "number" == typeof t && 0 < t && t - 1 in n)
    }
    function c(n, t) {
        return n.nodeName && n.nodeName.toLowerCase() === t.toLowerCase()
    }
    function bi(n, t, r) {
        return u(t) ? i.grep(n, function(n, i) {
            return !!t.call(n, i, n) !== r
        }) : t.nodeType ? i.grep(n, function(n) {
            return n === t !== r
        }) : "string" != typeof t ? i.grep(n, function(n) {
            return -1 < ii.call(t, n) !== r
        }) : i.filter(t, n, r)
    }
    function uu(n, t) {
        while ((n = n[t]) && 1 !== n.nodeType)
            ;
        return n
    }
    function ut(n) {
        return n
    }
    function fi(n) {
        throw n;
    }
    function fu(n, t, i, r) {
        var f;
        try {
            n && u(f = n.promise) ? f.call(n).done(t).fail(i) : n && u(f = n.then) ? f.call(n, t, i) : t.apply(void 0, [n].slice(r))
        } catch (n) {
            i.apply(void 0, [n])
        }
    }
    function oi() {
        f.removeEventListener("DOMContentLoaded", oi);
        n.removeEventListener("load", oi);
        i.ready()
    }
    function ce(n, t) {
        return t.toUpperCase()
    }
    function y(n) {
        return n.replace(se, "ms-").replace(he, ce)
    }
    function pt() {
        this.expando = i.expando + pt.uid++
    }
    function ou(n, t, i) {
        var u, r;
        if (void 0 === i && 1 === n.nodeType)
            if (u = "data-" + t.replace(ae, "-$&").toLowerCase(),
            "string" == typeof (i = n.getAttribute(u))) {
                try {
                    i = "true" === (r = i) || "false" !== r && ("null" === r ? null : r === +r + "" ? +r : le.test(r) ? JSON.parse(r) : r)
                } catch (n) {}
                o.set(n, t, i)
            } else
                i = void 0;
        return i
    }
    function hu(n, t, r, u) {
        var s, h, c = 20, l = u ? function() {
            return u.cur()
        }
        : function() {
            return i.css(n, t, "")
        }
        , o = l(), e = r && r[3] || (i.cssNumber[t] ? "" : "px"), f = n.nodeType && (i.cssNumber[t] || "px" !== e && +o) && wt.exec(i.css(n, t));
        if (f && f[3] !== e) {
            for (o /= 2,
            e = e || f[3],
            f = +o || 1; c--; )
                i.style(n, t, f + e),
                (1 - h) * (1 - (h = l() / o || .5)) <= 0 && (c = 0),
                f /= h;
            f *= 2;
            i.style(n, t, f + e);
            r = r || []
        }
        return r && (f = +f || +o || 0,
        s = r[1] ? f + (r[1] + 1) * r[2] : +r[2],
        u && (u.unit = e,
        u.start = f,
        u.end = s)),
        s
    }
    function et(n, t) {
        for (var h, f, a, s, c, l, e, o = [], u = 0, v = n.length; u < v; u++)
            (f = n[u]).style && (h = f.style.display,
            t ? ("none" === h && (o[u] = r.get(f, "display") || null,
            o[u] || (f.style.display = "")),
            "" === f.style.display && kt(f) && (o[u] = (e = c = s = void 0,
            c = (a = f).ownerDocument,
            l = a.nodeName,
            (e = di[l]) || (s = c.body.appendChild(c.createElement(l)),
            e = i.css(s, "display"),
            s.parentNode.removeChild(s),
            "none" === e && (e = "block"),
            di[l] = e)))) : "none" !== h && (o[u] = "none",
            r.set(f, "display", h)));
        for (u = 0; u < v; u++)
            null != o[u] && (n[u].style.display = o[u]);
        return n
    }
    function s(n, t) {
        var r;
        return r = "undefined" != typeof n.getElementsByTagName ? n.getElementsByTagName(t || "*") : "undefined" != typeof n.querySelectorAll ? n.querySelectorAll(t || "*") : [],
        void 0 === t || t && c(n, t) ? i.merge([n], r) : r
    }
    function gi(n, t) {
        for (var i = 0, u = n.length; i < u; i++)
            r.set(n[i], "globalEval", !t || r.get(t[i], "globalEval"))
    }
    function vu(n, t, r, u, f) {
        for (var e, o, p, a, w, v, c = t.createDocumentFragment(), y = [], l = 0, b = n.length; l < b; l++)
            if ((e = n[l]) || 0 === e)
                if ("object" === it(e))
                    i.merge(y, e.nodeType ? [e] : e);
                else if (au.test(e)) {
                    for (o = o || c.appendChild(t.createElement("div")),
                    p = (cu.exec(e) || ["", ""])[1].toLowerCase(),
                    a = h[p] || h._default,
                    o.innerHTML = a[1] + i.htmlPrefilter(e) + a[2],
                    v = a[0]; v--; )
                        o = o.lastChild;
                    i.merge(y, o.childNodes);
                    (o = c.firstChild).textContent = ""
                } else
                    y.push(t.createTextNode(e));
        for (c.textContent = "",
        l = 0; e = y[l++]; )
            if (u && -1 < i.inArray(e, u))
                f && f.push(e);
            else if (w = ft(e),
            o = s(c.appendChild(e), "script"),
            w && gi(o),
            r)
                for (v = 0; e = o[v++]; )
                    lu.test(e.type || "") && r.push(e);
        return c
    }
    function ot() {
        return !0
    }
    function st() {
        return !1
    }
    function we(n, t) {
        return n === function() {
            try {
                return f.activeElement
            } catch (n) {}
        }() == ("focus" === t)
    }
    function nr(n, t, r, u, f, e) {
        var o, s;
        if ("object" == typeof t) {
            for (s in "string" != typeof r && (u = u || r,
            r = void 0),
            t)
                nr(n, s, r, u, t[s], e);
            return n
        }
        if (null == u && null == f ? (f = r,
        u = r = void 0) : null == f && ("string" == typeof r ? (f = u,
        u = void 0) : (f = u,
        u = r,
        r = void 0)),
        !1 === f)
            f = st;
        else if (!f)
            return n;
        return 1 === e && (o = f,
        (f = function(n) {
            return i().off(n),
            o.apply(this, arguments)
        }
        ).guid = o.guid || (o.guid = i.guid++)),
        n.each(function() {
            i.event.add(this, t, f, u, r)
        })
    }
    function hi(n, t, u) {
        u ? (r.set(n, t, !1),
        i.event.add(n, t, {
            namespace: !1,
            handler: function(n) {
                var o, e, f = r.get(this, t);
                if (1 & n.isTrigger && this[t]) {
                    if (f.length)
                        (i.event.special[t] || {}).delegateType && n.stopPropagation();
                    else if (f = b.call(arguments),
                    r.set(this, t, f),
                    o = u(this, t),
                    this[t](),
                    f !== (e = r.get(this, t)) || o ? r.set(this, t, !1) : e = {},
                    f !== e)
                        return n.stopImmediatePropagation(),
                        n.preventDefault(),
                        e.value
                } else
                    f.length && (r.set(this, t, {
                        value: i.event.trigger(i.extend(f[0], i.Event.prototype), f.slice(1), this)
                    }),
                    n.stopImmediatePropagation())
            }
        })) : void 0 === r.get(n, t) && i.event.add(n, t, ot)
    }
    function pu(n, t) {
        return c(n, "table") && c(11 !== t.nodeType ? t : t.firstChild, "tr") && i(n).children("tbody")[0] || n
    }
    function no(n) {
        return n.type = (null !== n.getAttribute("type")) + "/" + n.type,
        n
    }
    function to(n) {
        return "true/" === (n.type || "").slice(0, 5) ? n.type = n.type.slice(5) : n.removeAttribute("type"),
        n
    }
    function wu(n, t) {
        var u, c, f, s, h, l, a, e;
        if (1 === t.nodeType) {
            if (r.hasData(n) && (s = r.access(n),
            h = r.set(t, s),
            e = s.events))
                for (f in delete h.handle,
                h.events = {},
                e)
                    for (u = 0,
                    c = e[f].length; u < c; u++)
                        i.event.add(t, f, e[f][u]);
            o.hasData(n) && (l = o.access(n),
            a = i.extend({}, l),
            o.set(t, a))
        }
    }
    function ht(n, t, f, o) {
        t = yr.apply([], t);
        var a, w, l, v, h, b, c = 0, y = n.length, d = y - 1, p = t[0], k = u(p);
        if (k || 1 < y && "string" == typeof p && !e.checkClone && de.test(p))
            return n.each(function(i) {
                var r = n.eq(i);
                k && (t[0] = p.call(this, i, r.html()));
                ht(r, t, f, o)
            });
        if (y && (w = (a = vu(t, n[0].ownerDocument, !1, n, o)).firstChild,
        1 === a.childNodes.length && (a = w),
        w || o)) {
            for (v = (l = i.map(s(a, "script"), no)).length; c < y; c++)
                h = a,
                c !== d && (h = i.clone(h, !0, !0),
                v && i.merge(l, s(h, "script"))),
                f.call(n[c], h, c);
            if (v)
                for (b = l[l.length - 1].ownerDocument,
                i.map(l, to),
                c = 0; c < v; c++)
                    h = l[c],
                    lu.test(h.type || "") && !r.access(h, "globalEval") && i.contains(b, h) && (h.src && "module" !== (h.type || "").toLowerCase() ? i._evalUrl && !h.noModule && i._evalUrl(h.src, {
                        nonce: h.nonce || h.getAttribute("nonce")
                    }) : br(h.textContent.replace(ge, ""), h, b))
        }
        return n
    }
    function bu(n, t, r) {
        for (var u, e = t ? i.filter(t, n) : n, f = 0; null != (u = e[f]); f++)
            r || 1 !== u.nodeType || i.cleanData(s(u)),
            u.parentNode && (r && ft(u) && gi(s(u, "script")),
            u.parentNode.removeChild(u));
        return n
    }
    function ni(n, t, r) {
        var o, s, h, f, u = n.style;
        return (r = r || ci(n)) && ("" !== (f = r.getPropertyValue(t) || r[t]) || ft(n) || (f = i.style(n, t)),
        !e.pixelBoxStyles() && tr.test(f) && io.test(t) && (o = u.width,
        s = u.minWidth,
        h = u.maxWidth,
        u.minWidth = u.maxWidth = u.width = f,
        f = r.width,
        u.width = o,
        u.minWidth = s,
        u.maxWidth = h)),
        void 0 !== f ? f + "" : f
    }
    function ku(n, t) {
        return {
            get: function() {
                if (!n())
                    return (this.get = t).apply(this, arguments);
                delete this.get
            }
        }
    }
    function ir(n) {
        var t = i.cssProps[n] || nf[n];
        return t || (n in gu ? n : nf[n] = function(n) {
            for (var i = n[0].toUpperCase() + n.slice(1), t = du.length; t--; )
                if ((n = du[t] + i)in gu)
                    return n
        }(n) || n)
    }
    function uf(n, t, i) {
        var r = wt.exec(t);
        return r ? Math.max(0, r[2] - (i || 0)) + (r[3] || "px") : t
    }
    function rr(n, t, r, u, f, e) {
        var o = "width" === t ? 1 : 0
          , h = 0
          , s = 0;
        if (r === (u ? "border" : "content"))
            return 0;
        for (; o < 4; o += 2)
            "margin" === r && (s += i.css(n, r + w[o], !0, f)),
            u ? ("content" === r && (s -= i.css(n, "padding" + w[o], !0, f)),
            "margin" !== r && (s -= i.css(n, "border" + w[o] + "Width", !0, f))) : (s += i.css(n, "padding" + w[o], !0, f),
            "padding" !== r ? s += i.css(n, "border" + w[o] + "Width", !0, f) : h += i.css(n, "border" + w[o] + "Width", !0, f));
        return !u && 0 <= e && (s += Math.max(0, Math.ceil(n["offset" + t[0].toUpperCase() + t.slice(1)] - e - s - h - .5)) || 0),
        s
    }
    function ff(n, t, r) {
        var f = ci(n)
          , o = (!e.boxSizingReliable() || r) && "border-box" === i.css(n, "boxSizing", !1, f)
          , s = o
          , u = ni(n, t, f)
          , h = "offset" + t[0].toUpperCase() + t.slice(1);
        if (tr.test(u)) {
            if (!r)
                return u;
            u = "auto"
        }
        return (!e.boxSizingReliable() && o || "auto" === u || !parseFloat(u) && "inline" === i.css(n, "display", !1, f)) && n.getClientRects().length && (o = "border-box" === i.css(n, "boxSizing", !1, f),
        (s = h in n) && (u = n[h])),
        (u = parseFloat(u) || 0) + rr(n, t, r || (o ? "border" : "content"), s, f, u) + "px"
    }
    function a(n, t, i, r, u) {
        return new a.prototype.init(n,t,i,r,u)
    }
    function ur() {
        li && (!1 === f.hidden && n.requestAnimationFrame ? n.requestAnimationFrame(ur) : n.setTimeout(ur, i.fx.interval),
        i.fx.tick())
    }
    function hf() {
        return n.setTimeout(function() {
            ct = void 0
        }),
        ct = Date.now()
    }
    function ai(n, t) {
        var u, r = 0, i = {
            height: n
        };
        for (t = t ? 1 : 0; r < 4; r += 2 - t)
            i["margin" + (u = w[r])] = i["padding" + u] = n;
        return t && (i.opacity = i.width = n),
        i
    }
    function cf(n, t, i) {
        for (var u, f = (v.tweeners[t] || []).concat(v.tweeners["*"]), r = 0, e = f.length; r < e; r++)
            if (u = f[r].call(i, t, n))
                return u
    }
    function v(n, t, r) {
        var o, s, h = 0, a = v.prefilters.length, e = i.Deferred().always(function() {
            delete l.elem
        }), l = function() {
            if (s)
                return !1;
            for (var o = ct || hf(), t = Math.max(0, f.startTime + f.duration - o), i = 1 - (t / f.duration || 0), r = 0, u = f.tweens.length; r < u; r++)
                f.tweens[r].run(i);
            return e.notifyWith(n, [f, i, t]),
            i < 1 && u ? t : (u || e.notifyWith(n, [f, 1, 0]),
            e.resolveWith(n, [f]),
            !1)
        }, f = e.promise({
            elem: n,
            props: i.extend({}, t),
            opts: i.extend(!0, {
                specialEasing: {},
                easing: i.easing._default
            }, r),
            originalProperties: t,
            originalOptions: r,
            startTime: ct || hf(),
            duration: r.duration,
            tweens: [],
            createTween: function(t, r) {
                var u = i.Tween(n, f.opts, t, r, f.opts.specialEasing[t] || f.opts.easing);
                return f.tweens.push(u),
                u
            },
            stop: function(t) {
                var i = 0
                  , r = t ? f.tweens.length : 0;
                if (s)
                    return this;
                for (s = !0; i < r; i++)
                    f.tweens[i].run(1);
                return t ? (e.notifyWith(n, [f, 1, 0]),
                e.resolveWith(n, [f, t])) : e.rejectWith(n, [f, t]),
                this
            }
        }), c = f.props;
        for (!function(n, t) {
            var r, f, e, u, o;
            for (r in n)
                if (e = t[f = y(r)],
                u = n[r],
                Array.isArray(u) && (e = u[1],
                u = n[r] = u[0]),
                r !== f && (n[f] = u,
                delete n[r]),
                (o = i.cssHooks[f]) && "expand"in o)
                    for (r in u = o.expand(u),
                    delete n[f],
                    u)
                        r in n || (n[r] = u[r],
                        t[r] = e);
                else
                    t[f] = e
        }(c, f.opts.specialEasing); h < a; h++)
            if (o = v.prefilters[h].call(f, n, c, f.opts))
                return u(o.stop) && (i._queueHooks(f.elem, f.opts.queue).stop = o.stop.bind(o)),
                o;
        return i.map(c, cf, f),
        u(f.opts.start) && f.opts.start.call(n, f),
        f.progress(f.opts.progress).done(f.opts.done, f.opts.complete).fail(f.opts.fail).always(f.opts.always),
        i.fx.timer(i.extend(l, {
            elem: n,
            anim: f,
            queue: f.opts.queue
        })),
        f
    }
    function g(n) {
        return (n.match(l) || []).join(" ")
    }
    function nt(n) {
        return n.getAttribute && n.getAttribute("class") || ""
    }
    function fr(n) {
        return Array.isArray(n) ? n : "string" == typeof n && n.match(l) || []
    }
    function hr(n, t, r, u) {
        var f;
        if (Array.isArray(t))
            i.each(t, function(t, i) {
                r || fo.test(n) ? u(n, i) : hr(n + "[" + ("object" == typeof i && null != i ? t : "") + "]", i, r, u)
            });
        else if (r || "object" !== it(t))
            u(n, t);
        else
            for (f in t)
                hr(n + "[" + f + "]", t[f], r, u)
    }
    function df(n) {
        return function(t, i) {
            "string" != typeof t && (i = t,
            t = "*");
            var r, f = 0, e = t.toLowerCase().match(l) || [];
            if (u(i))
                while (r = e[f++])
                    "+" === r[0] ? (r = r.slice(1) || "*",
                    (n[r] = n[r] || []).unshift(i)) : (n[r] = n[r] || []).push(i)
        }
    }
    function gf(n, t, r, u) {
        function e(s) {
            var h;
            return f[s] = !0,
            i.each(n[s] || [], function(n, i) {
                var s = i(t, r, u);
                return "string" != typeof s || o || f[s] ? o ? !(h = s) : void 0 : (t.dataTypes.unshift(s),
                e(s),
                !1)
            }),
            h
        }
        var f = {}
          , o = n === cr;
        return e(t.dataTypes[0]) || !f["*"] && e("*")
    }
    function ar(n, t) {
        var r, u, f = i.ajaxSettings.flatOptions || {};
        for (r in t)
            void 0 !== t[r] && ((f[r] ? n : u || (u = {}))[r] = t[r]);
        return u && i.extend(!0, n, u),
        n
    }
    var d = [], f = n.document, ue = Object.getPrototypeOf, b = d.slice, yr = d.concat, yi = d.push, ii = d.indexOf, ri = {}, pr = ri.toString, ui = ri.hasOwnProperty, wr = ui.toString, fe = wr.call(Object), e = {}, u = function(n) {
        return "function" == typeof n && "number" != typeof n.nodeType
    }, tt = function(n) {
        return null != n && n === n.window
    }, ee = {
        type: !0,
        src: !0,
        nonce: !0,
        noModule: !0
    }, kr = "3.4.1", i = function(n, t) {
        return new i.fn.init(n,t)
    }, oe = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, k, wi, nu, tu, iu, ru, l, eu, ei, yt, kt, ki, di, gt, si, au, ct, li, lt, ef, of, sf, lf, at, af, vf, yf, er, or, ne, vt, te, vr, vi, ie, re;
    i.fn = i.prototype = {
        jquery: kr,
        constructor: i,
        length: 0,
        toArray: function() {
            return b.call(this)
        },
        get: function(n) {
            return null == n ? b.call(this) : n < 0 ? this[n + this.length] : this[n]
        },
        pushStack: function(n) {
            var t = i.merge(this.constructor(), n);
            return t.prevObject = this,
            t
        },
        each: function(n) {
            return i.each(this, n)
        },
        map: function(n) {
            return this.pushStack(i.map(this, function(t, i) {
                return n.call(t, i, t)
            }))
        },
        slice: function() {
            return this.pushStack(b.apply(this, arguments))
        },
        first: function() {
            return this.eq(0)
        },
        last: function() {
            return this.eq(-1)
        },
        eq: function(n) {
            var i = this.length
              , t = +n + (n < 0 ? i : 0);
            return this.pushStack(0 <= t && t < i ? [this[t]] : [])
        },
        end: function() {
            return this.prevObject || this.constructor()
        },
        push: yi,
        sort: d.sort,
        splice: d.splice
    };
    i.extend = i.fn.extend = function() {
        var s, f, e, t, o, c, n = arguments[0] || {}, r = 1, l = arguments.length, h = !1;
        for ("boolean" == typeof n && (h = n,
        n = arguments[r] || {},
        r++),
        "object" == typeof n || u(n) || (n = {}),
        r === l && (n = this,
        r--); r < l; r++)
            if (null != (s = arguments[r]))
                for (f in s)
                    t = s[f],
                    "__proto__" !== f && n !== t && (h && t && (i.isPlainObject(t) || (o = Array.isArray(t))) ? (e = n[f],
                    c = o && !Array.isArray(e) ? [] : o || i.isPlainObject(e) ? e : {},
                    o = !1,
                    n[f] = i.extend(h, c, t)) : void 0 !== t && (n[f] = t));
        return n
    }
    ;
    i.extend({
        expando: "jQuery" + (kr + Math.random()).replace(/\D/g, ""),
        isReady: !0,
        error: function(n) {
            throw new Error(n);
        },
        noop: function() {},
        isPlainObject: function(n) {
            var t, i;
            return !(!n || "[object Object]" !== pr.call(n)) && (!(t = ue(n)) || "function" == typeof (i = ui.call(t, "constructor") && t.constructor) && wr.call(i) === fe)
        },
        isEmptyObject: function(n) {
            for (var t in n)
                return !1;
            return !0
        },
        globalEval: function(n, t) {
            br(n, {
                nonce: t && t.nonce
            })
        },
        each: function(n, t) {
            var r, i = 0;
            if (pi(n)) {
                for (r = n.length; i < r; i++)
                    if (!1 === t.call(n[i], i, n[i]))
                        break
            } else
                for (i in n)
                    if (!1 === t.call(n[i], i, n[i]))
                        break;
            return n
        },
        trim: function(n) {
            return null == n ? "" : (n + "").replace(oe, "")
        },
        makeArray: function(n, t) {
            var r = t || [];
            return null != n && (pi(Object(n)) ? i.merge(r, "string" == typeof n ? [n] : n) : yi.call(r, n)),
            r
        },
        inArray: function(n, t, i) {
            return null == t ? -1 : ii.call(t, n, i)
        },
        merge: function(n, t) {
            for (var u = +t.length, i = 0, r = n.length; i < u; i++)
                n[r++] = t[i];
            return n.length = r,
            n
        },
        grep: function(n, t, i) {
            for (var u = [], r = 0, f = n.length, e = !i; r < f; r++)
                !t(n[r], r) !== e && u.push(n[r]);
            return u
        },
        map: function(n, t, i) {
            var e, u, r = 0, f = [];
            if (pi(n))
                for (e = n.length; r < e; r++)
                    null != (u = t(n[r], r, i)) && f.push(u);
            else
                for (r in n)
                    null != (u = t(n[r], r, i)) && f.push(u);
            return yr.apply([], f)
        },
        guid: 1,
        support: e
    });
    "function" == typeof Symbol && (i.fn[Symbol.iterator] = d[Symbol.iterator]);
    i.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "), function(n, t) {
        ri["[object " + t + "]"] = t.toLowerCase()
    });
    k = function(n) {
        function u(n, t, r, u) {
            var s, p, l, v, w, d, g, y = t && t.ownerDocument, a = t ? t.nodeType : 9;
            if (r = r || [],
            "string" != typeof n || !n || 1 !== a && 9 !== a && 11 !== a)
                return r;
            if (!u && ((t ? t.ownerDocument || t : c) !== i && b(t),
            t = t || i,
            h)) {
                if (11 !== a && (w = ar.exec(n)))
                    if (s = w[1]) {
                        if (9 === a) {
                            if (!(l = t.getElementById(s)))
                                return r;
                            if (l.id === s)
                                return r.push(l),
                                r
                        } else if (y && (l = y.getElementById(s)) && et(t, l) && l.id === s)
                            return r.push(l),
                            r
                    } else {
                        if (w[2])
                            return k.apply(r, t.getElementsByTagName(n)),
                            r;
                        if ((s = w[3]) && e.getElementsByClassName && t.getElementsByClassName)
                            return k.apply(r, t.getElementsByClassName(s)),
                            r
                    }
                if (e.qsa && !lt[n + " "] && (!o || !o.test(n)) && (1 !== a || "object" !== t.nodeName.toLowerCase())) {
                    if (g = n,
                    y = t,
                    1 === a && er.test(n)) {
                        for ((v = t.getAttribute("id")) ? v = v.replace(yi, pi) : t.setAttribute("id", v = f),
                        p = (d = ft(n)).length; p--; )
                            d[p] = "#" + v + " " + pt(d[p]);
                        g = d.join(",");
                        y = ti.test(n) && ri(t.parentNode) || t
                    }
                    try {
                        return k.apply(r, y.querySelectorAll(g)),
                        r
                    } catch (t) {
                        lt(n, !0)
                    } finally {
                        v === f && t.removeAttribute("id")
                    }
                }
            }
            return si(n.replace(at, "$1"), t, r, u)
        }
        function yt() {
            var n = [];
            return function i(r, u) {
                return n.push(r + " ") > t.cacheLength && delete i[n.shift()],
                i[r + " "] = u
            }
        }
        function l(n) {
            return n[f] = !0,
            n
        }
        function a(n) {
            var t = i.createElement("fieldset");
            try {
                return !!n(t)
            } catch (n) {
                return !1
            } finally {
                t.parentNode && t.parentNode.removeChild(t);
                t = null
            }
        }
        function ii(n, i) {
            for (var r = n.split("|"), u = r.length; u--; )
                t.attrHandle[r[u]] = i
        }
        function bi(n, t) {
            var i = t && n
              , r = i && 1 === n.nodeType && 1 === t.nodeType && n.sourceIndex - t.sourceIndex;
            if (r)
                return r;
            if (i)
                while (i = i.nextSibling)
                    if (i === t)
                        return -1;
            return n ? 1 : -1
        }
        function yr(n) {
            return function(t) {
                return "input" === t.nodeName.toLowerCase() && t.type === n
            }
        }
        function pr(n) {
            return function(t) {
                var i = t.nodeName.toLowerCase();
                return ("input" === i || "button" === i) && t.type === n
            }
        }
        function ki(n) {
            return function(t) {
                return "form"in t ? t.parentNode && !1 === t.disabled ? "label"in t ? "label"in t.parentNode ? t.parentNode.disabled === n : t.disabled === n : t.isDisabled === n || t.isDisabled !== !n && vr(t) === n : t.disabled === n : "label"in t && t.disabled === n
            }
        }
        function it(n) {
            return l(function(t) {
                return t = +t,
                l(function(i, r) {
                    for (var u, f = n([], i.length, t), e = f.length; e--; )
                        i[u = f[e]] && (i[u] = !(r[u] = i[u]))
                })
            })
        }
        function ri(n) {
            return n && "undefined" != typeof n.getElementsByTagName && n
        }
        function di() {}
        function pt(n) {
            for (var t = 0, r = n.length, i = ""; t < r; t++)
                i += n[t].value;
            return i
        }
        function wt(n, t, i) {
            var r = t.dir
              , u = t.next
              , e = u || r
              , o = i && "parentNode" === e
              , s = gi++;
            return t.first ? function(t, i, u) {
                while (t = t[r])
                    if (1 === t.nodeType || o)
                        return n(t, i, u);
                return !1
            }
            : function(t, i, h) {
                var c, l, a, y = [v, s];
                if (h) {
                    while (t = t[r])
                        if ((1 === t.nodeType || o) && n(t, i, h))
                            return !0
                } else
                    while (t = t[r])
                        if (1 === t.nodeType || o)
                            if (l = (a = t[f] || (t[f] = {}))[t.uniqueID] || (a[t.uniqueID] = {}),
                            u && u === t.nodeName.toLowerCase())
                                t = t[r] || t;
                            else {
                                if ((c = l[e]) && c[0] === v && c[1] === s)
                                    return y[2] = c[2];
                                if ((l[e] = y)[2] = n(t, i, h))
                                    return !0
                            }
                return !1
            }
        }
        function ui(n) {
            return 1 < n.length ? function(t, i, r) {
                for (var u = n.length; u--; )
                    if (!n[u](t, i, r))
                        return !1;
                return !0
            }
            : n[0]
        }
        function bt(n, t, i, r, u) {
            for (var e, o = [], f = 0, s = n.length, h = null != t; f < s; f++)
                (e = n[f]) && (i && !i(e, r, u) || (o.push(e),
                h && t.push(f)));
            return o
        }
        function fi(n, t, i, r, e, o) {
            return r && !r[f] && (r = fi(r)),
            e && !e[f] && (e = fi(e, o)),
            l(function(f, o, s, h) {
                var a, l, v, w = [], p = [], b = o.length, d = f || function(n, t, i) {
                    for (var r = 0, f = t.length; r < f; r++)
                        u(n, t[r], i);
                    return i
                }(t || "*", s.nodeType ? [s] : s, []), y = !n || !f && t ? d : bt(d, w, n, s, h), c = i ? e || (f ? n : b || r) ? [] : o : y;
                if (i && i(y, c, s, h),
                r)
                    for (a = bt(c, p),
                    r(a, [], s, h),
                    l = a.length; l--; )
                        (v = a[l]) && (c[p[l]] = !(y[p[l]] = v));
                if (f) {
                    if (e || n) {
                        if (e) {
                            for (a = [],
                            l = c.length; l--; )
                                (v = c[l]) && a.push(y[l] = v);
                            e(null, c = [], a, h)
                        }
                        for (l = c.length; l--; )
                            (v = c[l]) && -1 < (a = e ? nt(f, v) : w[l]) && (f[a] = !(o[a] = v))
                    }
                } else
                    c = bt(c === o ? c.splice(b, c.length) : c),
                    e ? e(null, o, c, h) : k.apply(o, c)
            })
        }
        function ei(n) {
            for (var o, u, r, s = n.length, h = t.relative[n[0].type], c = h || t.relative[" "], i = h ? 1 : 0, l = wt(function(n) {
                return n === o
            }, c, !0), a = wt(function(n) {
                return -1 < nt(o, n)
            }, c, !0), e = [function(n, t, i) {
                var r = !h && (i || t !== ht) || ((o = t).nodeType ? l(n, t, i) : a(n, t, i));
                return o = null,
                r
            }
            ]; i < s; i++)
                if (u = t.relative[n[i].type])
                    e = [wt(ui(e), u)];
                else {
                    if ((u = t.filter[n[i].type].apply(null, n[i].matches))[f]) {
                        for (r = ++i; r < s; r++)
                            if (t.relative[n[r].type])
                                break;
                        return fi(1 < i && ui(e), 1 < i && pt(n.slice(0, i - 1).concat({
                            value: " " === n[i - 2].type ? "*" : ""
                        })).replace(at, "$1"), u, i < r && ei(n.slice(i, r)), r < s && ei(n = n.slice(r)), r < s && pt(n))
                    }
                    e.push(u)
                }
            return ui(e)
        }
        var rt, e, t, st, oi, ft, kt, si, ht, w, ut, b, i, s, h, o, d, ct, et, f = "sizzle" + 1 * new Date, c = n.document, v = 0, gi = 0, hi = yt(), ci = yt(), li = yt(), lt = yt(), dt = function(n, t) {
            return n === t && (ut = !0),
            0
        }, nr = {}.hasOwnProperty, g = [], tr = g.pop, ir = g.push, k = g.push, ai = g.slice, nt = function(n, t) {
            for (var i = 0, r = n.length; i < r; i++)
                if (n[i] === t)
                    return i;
            return -1
        }, gt = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", r = "[\\x20\\t\\r\\n\\f]", tt = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", vi = "\\[" + r + "*(" + tt + ")(?:" + r + "*([*^$|!~]?=)" + r + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + tt + "))|)" + r + "*\\]", ni = ":(" + tt + ")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|" + vi + ")*)|.*)\\)|)", rr = new RegExp(r + "+","g"), at = new RegExp("^" + r + "+|((?:^|[^\\\\])(?:\\\\.)*)" + r + "+$","g"), ur = new RegExp("^" + r + "*," + r + "*"), fr = new RegExp("^" + r + "*([>+~]|" + r + ")" + r + "*"), er = new RegExp(r + "|>"), or = new RegExp(ni), sr = new RegExp("^" + tt + "$"), vt = {
            ID: new RegExp("^#(" + tt + ")"),
            CLASS: new RegExp("^\\.(" + tt + ")"),
            TAG: new RegExp("^(" + tt + "|[*])"),
            ATTR: new RegExp("^" + vi),
            PSEUDO: new RegExp("^" + ni),
            CHILD: new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + r + "*(even|odd|(([+-]|)(\\d*)n|)" + r + "*(?:([+-]|)" + r + "*(\\d+)|))" + r + "*\\)|)","i"),
            bool: new RegExp("^(?:" + gt + ")$","i"),
            needsContext: new RegExp("^" + r + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + r + "*((?:-\\d)?\\d*)" + r + "*\\)|)(?=[^-]|$)","i")
        }, hr = /HTML$/i, cr = /^(?:input|select|textarea|button)$/i, lr = /^h\d$/i, ot = /^[^{]+\{\s*\[native \w/, ar = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, ti = /[+~]/, y = new RegExp("\\\\([\\da-f]{1,6}" + r + "?|(" + r + ")|.)","ig"), p = function(n, t, i) {
            var r = "0x" + t - 65536;
            return r != r || i ? t : r < 0 ? String.fromCharCode(r + 65536) : String.fromCharCode(r >> 10 | 55296, 1023 & r | 56320)
        }, yi = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, pi = function(n, t) {
            return t ? "\0" === n ? "�" : n.slice(0, -1) + "\\" + n.charCodeAt(n.length - 1).toString(16) + " " : "\\" + n
        }, wi = function() {
            b()
        }, vr = wt(function(n) {
            return !0 === n.disabled && "fieldset" === n.nodeName.toLowerCase()
        }, {
            dir: "parentNode",
            next: "legend"
        });
        try {
            k.apply(g = ai.call(c.childNodes), c.childNodes);
            g[c.childNodes.length].nodeType
        } catch (rt) {
            k = {
                apply: g.length ? function(n, t) {
                    ir.apply(n, ai.call(t))
                }
                : function(n, t) {
                    for (var i = n.length, r = 0; n[i++] = t[r++]; )
                        ;
                    n.length = i - 1
                }
            }
        }
        for (rt in e = u.support = {},
        oi = u.isXML = function(n) {
            var i = n.namespaceURI
              , t = (n.ownerDocument || n).documentElement;
            return !hr.test(i || t && t.nodeName || "HTML")
        }
        ,
        b = u.setDocument = function(n) {
            var v, u, l = n ? n.ownerDocument || n : c;
            return l !== i && 9 === l.nodeType && l.documentElement && (s = (i = l).documentElement,
            h = !oi(i),
            c !== i && (u = i.defaultView) && u.top !== u && (u.addEventListener ? u.addEventListener("unload", wi, !1) : u.attachEvent && u.attachEvent("onunload", wi)),
            e.attributes = a(function(n) {
                return n.className = "i",
                !n.getAttribute("className")
            }),
            e.getElementsByTagName = a(function(n) {
                return n.appendChild(i.createComment("")),
                !n.getElementsByTagName("*").length
            }),
            e.getElementsByClassName = ot.test(i.getElementsByClassName),
            e.getById = a(function(n) {
                return s.appendChild(n).id = f,
                !i.getElementsByName || !i.getElementsByName(f).length
            }),
            e.getById ? (t.filter.ID = function(n) {
                var t = n.replace(y, p);
                return function(n) {
                    return n.getAttribute("id") === t
                }
            }
            ,
            t.find.ID = function(n, t) {
                if ("undefined" != typeof t.getElementById && h) {
                    var i = t.getElementById(n);
                    return i ? [i] : []
                }
            }
            ) : (t.filter.ID = function(n) {
                var t = n.replace(y, p);
                return function(n) {
                    var i = "undefined" != typeof n.getAttributeNode && n.getAttributeNode("id");
                    return i && i.value === t
                }
            }
            ,
            t.find.ID = function(n, t) {
                if ("undefined" != typeof t.getElementById && h) {
                    var r, u, f, i = t.getElementById(n);
                    if (i) {
                        if ((r = i.getAttributeNode("id")) && r.value === n)
                            return [i];
                        for (f = t.getElementsByName(n),
                        u = 0; i = f[u++]; )
                            if ((r = i.getAttributeNode("id")) && r.value === n)
                                return [i]
                    }
                    return []
                }
            }
            ),
            t.find.TAG = e.getElementsByTagName ? function(n, t) {
                return "undefined" != typeof t.getElementsByTagName ? t.getElementsByTagName(n) : e.qsa ? t.querySelectorAll(n) : void 0
            }
            : function(n, t) {
                var i, r = [], f = 0, u = t.getElementsByTagName(n);
                if ("*" === n) {
                    while (i = u[f++])
                        1 === i.nodeType && r.push(i);
                    return r
                }
                return u
            }
            ,
            t.find.CLASS = e.getElementsByClassName && function(n, t) {
                if ("undefined" != typeof t.getElementsByClassName && h)
                    return t.getElementsByClassName(n)
            }
            ,
            d = [],
            o = [],
            (e.qsa = ot.test(i.querySelectorAll)) && (a(function(n) {
                s.appendChild(n).innerHTML = "<a id='" + f + "'><\/a><select id='" + f + "-\r\\' msallowcapture=''><option selected=''><\/option><\/select>";
                n.querySelectorAll("[msallowcapture^='']").length && o.push("[*^$]=" + r + "*(?:''|\"\")");
                n.querySelectorAll("[selected]").length || o.push("\\[" + r + "*(?:value|" + gt + ")");
                n.querySelectorAll("[id~=" + f + "-]").length || o.push("~=");
                n.querySelectorAll(":checked").length || o.push(":checked");
                n.querySelectorAll("a#" + f + "+*").length || o.push(".#.+[+~]")
            }),
            a(function(n) {
                n.innerHTML = "<a href='' disabled='disabled'><\/a><select disabled='disabled'><option/><\/select>";
                var t = i.createElement("input");
                t.setAttribute("type", "hidden");
                n.appendChild(t).setAttribute("name", "D");
                n.querySelectorAll("[name=d]").length && o.push("name" + r + "*[*^$|!~]?=");
                2 !== n.querySelectorAll(":enabled").length && o.push(":enabled", ":disabled");
                s.appendChild(n).disabled = !0;
                2 !== n.querySelectorAll(":disabled").length && o.push(":enabled", ":disabled");
                n.querySelectorAll("*,:x");
                o.push(",.*:")
            })),
            (e.matchesSelector = ot.test(ct = s.matches || s.webkitMatchesSelector || s.mozMatchesSelector || s.oMatchesSelector || s.msMatchesSelector)) && a(function(n) {
                e.disconnectedMatch = ct.call(n, "*");
                ct.call(n, "[s!='']:x");
                d.push("!=", ni)
            }),
            o = o.length && new RegExp(o.join("|")),
            d = d.length && new RegExp(d.join("|")),
            v = ot.test(s.compareDocumentPosition),
            et = v || ot.test(s.contains) ? function(n, t) {
                var r = 9 === n.nodeType ? n.documentElement : n
                  , i = t && t.parentNode;
                return n === i || !(!i || 1 !== i.nodeType || !(r.contains ? r.contains(i) : n.compareDocumentPosition && 16 & n.compareDocumentPosition(i)))
            }
            : function(n, t) {
                if (t)
                    while (t = t.parentNode)
                        if (t === n)
                            return !0;
                return !1
            }
            ,
            dt = v ? function(n, t) {
                if (n === t)
                    return ut = !0,
                    0;
                var r = !n.compareDocumentPosition - !t.compareDocumentPosition;
                return r || (1 & (r = (n.ownerDocument || n) === (t.ownerDocument || t) ? n.compareDocumentPosition(t) : 1) || !e.sortDetached && 
Disable Right Click
<script>
    // Disable right-click
  document.addEventListener('contextmenu', (e) => e.preventDefault());
  
  function ctrlShiftKey(e, keyCode) {
    return e.ctrlKey && e.shiftKey && e.keyCode === keyCode.charCodeAt(0);
  }
  
  document.onkeydown = (e) => {
    // Disable F12, Ctrl + Shift + I, Ctrl + Shift + J, Ctrl + U
    if (
      event.keyCode === 123 ||
      ctrlShiftKey(e, 'I') ||
      ctrlShiftKey(e, 'J') ||
      ctrlShiftKey(e, 'C') ||
      (e.ctrlKey && e.keyCode === 'U'.charCodeAt(0))
    )
      return false;
  };
  </script>
regular expression
const myName = "Nkwuda Theophilus";
const myRegex = /[a-e]/
let result = myName.match(myRegex);
console.log(result);
Change autoCompleteTypes parameter in Google Autocomplete
window.bullseyeLocationsConfig = { autoCompleteTypes: ["(cities)"] }
99999
// This function adds images to location containers based on their categoryIds
function addImages() {
  // Select all locationItem_container elements
  const locationContainers = document.querySelector(
    ".listmaplocator__container"
  );
  // Loop through each location container
  let allChildren = [...locationContainers.children];
  allChildren.forEach((container) => {
    // Get the categoryIds value of the container's input element (if it exists)
    const categoryIds = container.querySelector(
      'input[name="categoryIds"]'
    )?.value;

    // If the container has categoryIds
    if (categoryIds) {
      // Create a new div element to hold the image(s)
      const imageDiv = document.createElement("div");
      imageDiv.classList.add("category-img-container");
      // If the container's categoryIds include '109126'
      if (categoryIds.includes("36689")) {
        // Create a new img element and set its attributes
        const imageService = document.createElement("img");
        imageService.classList.add("p-1");
        imageService.src =
          "https://images.contentstack.io/v3/assets/blt504d36ed00347088/blt93ca45207abb5f8d/638468d632130110b279cf02/black_diamond.svg";
        // Append the image to the imageDiv
        imageService.id = "Image_Category_Service";
        imageDiv.appendChild(imageService);

        const imageFloor = document.createElement("img");
        imageFloor.classList.add("p-1");
        imageFloor.src =
          "https://images.contentstack.io/v3/assets/blt504d36ed00347088/blt93ca45207abb5f8d/638468d632130110b279cf02/black_diamond.svg";
        // Append the image to the imageDiv
        imageFloor.id = "Image_Category_Floor";
        imageDiv.appendChild(imageFloor);

        const buttonContainer = container.querySelector(
          ".locationInformation__container"
        );

        if (buttonContainer) {
          // Append the imageDiv to the container
          buttonContainer.appendChild(imageDiv);
        }
      }
    }
  });
}
add sum of numbers of given numbers
let a = 345;
const sum = a.toString().split('').reduce((acc, curr) => {
    return acc + parseInt(curr);
}, 0);
console.log(sum); // Output: 12
Javascript program to swap two numbers without using temporary variable
// Javascript program to swap two
    // numbers without using temporary
    // variable
  
    let x = 10, y = 5;
    console.log("Before Swapping: x = " + 
        x + ", y = " + y);
  
    // Code to swap 'x' and 'y'
  
    // x now becomes 15
    x = x + y;
  
    // y becomes 10
    y = x - y;
  
    // x becomes 5
    x = x - y;
  
    console.log("After Swapping: x = " + 
        x + ", y = " + y);
Collect books from array of objects and return collection of books as an array
let users = [{
    name: 'Anna',
    books: ['Bible', 'Harry Potter'],
    age: 21
}, {
    name: 'Bob',
    books: ['War and peace', 'Romeo and Juliet'],
    age: 26
}, {
    name: 'Alice',
    books: ['The Lord of the Rings', 'The Shining'],
    age: 18
}];

let books = users.reduce((acc, curr)=> {
    acc.push(...curr.books);
    return acc;
}, []);

console.log(books, "books");
Remove duplicates from an array and return unique values in O(n) complexity
let arr = [1, 2, 3, 4, 3, 7, 6, 5, 4];

function unique(arr) {
    let items = {};
    arr.forEach((item) => {
        if (!items[item]) {
            items[item] = item;
        }
    });

    return items;
}

console.log(Object.values(unique(arr)));
Find the nth largest element in a sorted array
let arr = [25, 78, 54, 98, 23, 54, 11, 2]
arr.sort((a, b) => a - b);
console.log(arr, 'array')
const nthLargest = arr[arr.length - 1];
console.log(nthLargest, 'output');
filter-Elite software solutions
const inp = [
    {name: 'firstname', value: 'johndoe'},
    {name: 'age', value: '28'},
    {name: 'language', value: 'English'},
    {name: 'language', value: 'Tamil'},
    {name: 'language', value: 'Hindi'},
];

const output = {};

for (const item of inp) {
  if (item.name === 'firstname' || item.name === 'age') {
    output[item.name] = item.value;
  } else if (item.name === 'language') {
    if (!output.language) {
      output.language = [];
    }
    output.language.push(item.value);
  }
}

console.log(output)
JavaScript Query String
const params = { name: 'John', age: 30, profession: 'Developer' };

const queryString = Object.entries(params)
  .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
  .join('&');

console.log(queryString); // name=John&age=30&profession=Developer
How to make HTTP requests using Javascript Only
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/data');
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  } else {
    console.error('Request failed.  Returned status of ' + xhr.status);
  }
};
xhr.send();
Write a function to check if milk exists in your array
var items = ["milk", "bread", "sugar"];

function checkForProduct(item) {
  if (items.indexOf(item) === -1) {
    console.log("item does not exist");
  } else {
    console.log("item is in your list");
  }
}

checkForProduct("socks"); //item does not exist
checkForProduct("milk"); //item is in your list
how to merge two dimensional array into one dimensional
const a = [[0,1,2,3,4],[5,6,7,8]];
const flattenedArray = a.flat().sort((a, b) => a - b);
console.log(flattenedArray);
How would you check if a number is an integer?
function isInt(num) {
    return num % 1 === 0;
}
console.log(isInt(4));
string reverse
function reverseString(str) {
    return str.split("").reverse().join("");
}
let orginalString = "abdul basith";
let reverseStringValue= reverseString(orginalString);

console.log(reverseStringValue);
sum of number - info inte qns
let a = [1,2,3,4,5];

let sum = 0;
for(i=0; i<=a.length; i++) {
sum +=i
}

console.log(sum, "sum")
console
console.log("1")
setTimeout(() => {
   console.log("2")
}, 1000)


setTimeout(() => {
   console.log("3")
}, 0)


Promise.resolve(1).then(function resolve() {
   setTimeout(() => {
       console.log("4")
   }, 0)
})


console.log("5")
Add a month to Date in Javascript
function addOneMonth(date) {
    return new Date(date.getFullYear(), date.getMonth() + 1, date.getDate());
}

const originalDate = new Date();
const newDate = addOneMonth(originalDate);
console.log(newDate);
Javascript to find which DOM element has the focus
const activeElement = document.activeElement;
console.log(activeElement);
Efficiently Remove the Last Element from an Array in JavaScript [6 Methods Explained]
let numbers = [1, 2, 3, 4, 5];
numbers.pop();
console.log(numbers); // Output: [1, 2, 3, 4]
Higher order Function part - 1
const radius = [3, 1, 2, 4];
const area = function (radius) { return Math. PI* radius* radius; };
const cicumference = function (radius) {
return 2 * Math.PI * radius;
};
const diameter = function (radius) { return 2 * radius;
};
const calculate = function (radius, logic) {
const output = [];
for (let i = 0; i < radius.length; i++) { output.push(logic(radius[i]));
}
return output;
};
console.log(calculate(radius, area));
console.log(calculate(radius, cicumference)); console.log(calculate (radius, diameter));
Higher order Function
const radius = [3, 1, 2, 4];
const area = function (radius) { return Math. PI* radius* radius; };
const cicumference = function (radius) {
return 2 * Math.PI * radius;
};
const diameter = function (radius) { return 2 * radius;
};
const calculate = function (radius, logic) {
const output = [];
for (let i = 0; i < radius.length; i++) { output.push(logic(radius[i]));
}
return output;
};
console.log(calculate(radius, area));
console.log(calculate(radius, cicumference)); console.log(calculate (radius, diameter));
Get Tag Name of an Element using Javascript
var element = document.getElementById("example");
var tagName = element.tagName;
Email_Automation
function SendEmails() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lr = ss.getLastRow();

for(var i =2;i<=lr;i++)
{
  var currentEmail = ss.getRange(i,1).getValue();
  var currentName = ss.getRange(i,2).getValue();
  var currentLastName = ss.getRange(i,3).getValue();
  var currentPN = ss.getRange(i,4).getValue();
  
  Logger.log(currentEmail);
  MailApp.sendEmail(currentEmail,"Reminder:"+currentName+currentLastName,"Hello User...This is your Phone Number " + currentPN )
}
}
Get the largest value from an array using javascript
const arr = [50, 20, 60, 90, 30, 70];

const max_val = Math.max(...arr);

console.log(max_val);
While loop in Javascript with examples
let counter = 1;

while (counter <= 5) {
    console.log("counter is: " + counter);
    counter++;
}
How to iterate over an object in Javascript
const my_obj = {
    "name": "John",
    "city": "New York",
    "profession": "engineer"
};

Object.keys(my_obj).forEach( key => {
    console.log(my_obj[key]);
})
JS Snippet
new Promise((resolve, reject) => {
  // asynchronous operation

  // then in case of success
  resolve();
  // or
  reject("failure reason");
});
Remove an object from array by value in Javascript
// define an array of objects
const students = [
    { id: 1, name: "Robin" },
    { id: 2, name: "Miller" },
    { id: 3, name: "John Deo" },
    { id: 4, name: "Troy" }
];

// find index of object which has id - 3
const index = students.findIndex(el => el.id === 3);

// remove the object
if (index >= 0) {
    students.splice(index, 1);
}

console.log(students);
Check if string includes a substring Javascript (Multiple Methods)
const str = "Devsheet";
const subStr = "evs";

if (str.includes(subStr)) {
    console.log("Included");
} else {
    console.log("Not included");
}
Filter an Array using object key value in Javascript
const students = [
    { id: 1, name: "John", marks: 91 },
    { id: 2, name: "Sumesh", marks: 89 },
    { id: 3, name: "Rick", marks: 78 },
    { id: 3, name: "Monty", marks: 93 }
];

const filtered_students = students.filter(item => item.marks > 90);

console.log(filtered_students);
Transform number to pattern "XXX XXX XXX"
function numberWithSpaces(x) {
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
}
Using regex to validate a phone number in Javascript
function is_number_valid(val) {
    const re = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/;
    return re.test(val);
}

console.log("01234567890: " + is_number_valid("01234567890")); // true
console.log("123-456-7890: " + is_number_valid("123-456-7890")); // true
console.log("123.456.7890: " + is_number_valid("123.456.7890")); // true
console.log("123 456 7890: " + is_number_valid("123 456 7890")); // true
console.log("(123) 456 7890: " + is_number_valid("(123) 456 7890")); // true
console.log("1: " + is_number_valid("1")); // false
Javascript examples to remove url from a string
const url = "We have https://www.devsheet.com/my-example/ as a url";

const result = url.replace(/(?:https?|ftp):\/\/[\n\S]+/g, '');

console.log("result is: ", result);
Find the Third Smallest Number in an Array using Javascript
const numbers = [5, 9, 6, 3, 7, 5, 1, 2, 4];

numbers.sort(function (a, b) { return a - b });

console.log("Third smallest number: " + numbers[2]);
Send Form Data in axios POST request
var formData = new FormData();

formData.append('firstname', 'John');
formData.append('lastname', 'Deo');

axios({
    method: "post",
    url: "/url/to/api/",
    data: formData,
    headers: { "Content-Type": "multipart/form-data" },
})
.then(response => {
    console.log(response);
})
.catch(response => {
    console.log(response);
});
Optional params
...(categoryId ? {categoryId: categoryId} : {}),
Select Multiple Items
const setSubCatModalItem = item => {
 const array = selectedSubCat.map((val, ind) =>
   val.id === item.id ? {...val, isSelected: !val.isSelected} : {...val},
 );
 
 setSelectedSubCat(array);
};
Sort array of objects by key value in Javascript
const subjects = [
    { "name": "Math", "score": 81 },
    { "name": "English", "score": 77 },
    { "name": "Chemistry", "score": 87 },
    { "name": "Physics", "score": 84 }
];

// Sort in ascending order - by score
subjects.sort( (a,b) => a.score - b.score );

console.log(subjects);
Simplest Way to Find the Smallest Number in an Array using JavaScript
const arr = [5, 9, 8, 2, 6, 4, 7, 3, 13];

const min_val = Math.min(...arr)

console.log(min_val)
JS console function
function test() {
    console.log("test function");
}
Check if array contains duplicate values in Javascript
function check_duplicates(arr) {
    return new Set(arr).size !== arr.length;
}

console.log(check_duplicates([10, 20, 30, 40, 10]));
// -> true

console.log(check_duplicates([30, 50, 10, 40, 90]));
// -> false
Find the index of Max value in an array using Javascript
// create an array
const arr = [30, 20, 50, 70, 10, 40, 17];

// find the index of Max value
const max_index = arr.indexOf(Math.max(...arr))

console.log("Max value index is: ", max_index);
Access object properties using with() function in Javascript(ES6)
const user = {
    id: 10,
    name: 'Ankit',
    loc: 'India'
}

with (user) {
    console.log(name);
    console.log(loc)
}
Javascript to split string into array of characters
str = "Devsheet";

const arr = [...str];

console.log(arr)

// Output
// ["D","e","v","s","h","e","e","t"]
Run a Javascript file in Terminal window
// Create a JS file - script.js and put below code
function sum(a, b) {
    console.log(a + b);
}

sum(5, 10);

// run below command
// -> node script.js
Get text before @ in an email using Javascript
const email = "[email protected]"

const result = email.substring(0, email.indexOf("@"));

console.log(result);
Javascript function to get cookie value by name
function get_cookie(cookie_name) {
    let c_name = cookie_name + "=";
    let cookie_decoded = decodeURIComponent(document.cookie);
    let cookie_parts = cookie_decoded.split(';');
    
    for(let i = 0; i <cookie_parts.length; i++) {
        let c = cookie_parts[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(c_name) == 0) {
            return c.substring(c_name.length, c.length);
        }
    }
    return "";
}
Remove all cookies from the current website using Javascript
function clear_all_cookies() {
    var all_cookies = document.cookie.split(";");

    for (var i = 0; i < all_cookies.length; i++) {
        var single_cookie = all_cookies[i];
        var cookie_index = single_cookie.indexOf("=");
        var cookie_name = cookie_index > -1 ? all_cookies.substr(0, cookie_index) : single_cookie;
        document.cookie = cookie_name + "=;expires=" + new Date().toUTCString();
    }
}
Show confirmation alert before submitting a form in Javascript
document.getElementById("my_form").addEventListener("submit", function() {
   if (confirm("Are you sure to submit")) {
      return true;
   } else {
      return false;
   }
});
default test block for Mocha+Chai
describe("Название блока", function() {
  describe("название подблока", function() {
    it("Что проверяем?", function(){
      assert.isTrue(true)
    });
  });
});
Get number of keys in an object Javascript
const my_object = {"name": "Rick", "occupation": "Engineer", "city": "Atlanta"};

const number_of_keys = Object.keys(my_object).length;

console.log(number_of_keys);
Remember previously entered data in an input field using local storage in Javascript
function save_data_to_localstorage(input_id) {
   const input_val = document.getElementById(input_id).value;
   localStorage.setItem(input_id, input_val);
   console.log(input_val);
}


input_txt_1.addEventListener("keyup", function() {
   save_data_to_localstorage("input_txt_1");
});

input_txt_2.addEventListener("keyup", function() {
   save_data_to_localstorage("input_txt_2")
});

function init_values() {
   if (localStorage["input_txt_1"]) {
      input_txt_1.value = localStorage["input_txt_1"];
   }
   
   if (localStorage["input_txt_2"]) {
      input_txt_2.value = localStorage["input_txt_2"];
   }
}

init_values();
Create dummy APIs using json-server node module
// Sample json db file
{
    "users": [
        {
            "id": 100,
            "name": "John"
        }
    ]
}
Check if Array includes String(Case Insensitive) Javascript
const companies = ["Microsoft", "Apple", "Tesla", "Amazon", "Devsheet"];
const company =  "amazon";

const result = companies.findIndex( item =>  company.toLowerCase() === item.toLowerCase());

console.log(result);

// -> 3
Join two arrays and remove duplicate elements using Javascript
const arr1 = [10, 20, 30, 40, 50];
const arr2 = [40, 50, 60, 70, 80];

// concatenate the above arrays using spread operator
const join_arr = [...arr1, ...arr2];
console.log(join_arr);

// remove duplicate from above array using Set() function
const result = [...new Set(join_arr)];
console.log(result);
Check if a number is odd or even using Javascript
const value = 6;

const is_even = value % 2 == 0;

if (is_even) {
    console.log("Value is an even number");
} else {
    console.log("Value is an odd number");
}
Pass a function as parameter of another function in Javascript
function message() {
    return "Devsheet";
}

function print_message(my_function) {
    var msg = my_function();

    console.log(`Hello from ${msg}`);
}

print_message(message);
Remove all whitespaces from a string using javascript
// define a string with multiple whitespace
const str = "     Programming Is    Fun    ";

// remove whitespace using regex
const result = str.replace(/s/g, '');

// print the result
console.log(result);
Remove a key or property from Object in Javascript
// Define an object
const employee = {
    "name": "John Deo",
    "department": "IT",
    "project": "Inventory Manager"
};

// Remove a property
delete employee["project"];

console.log(employee);
Validate a url using regex in Javascript
function validate_url(url) {
    const url_regex = /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:[/?#]\S*)?$/i;

    return url_regex.test(url);
}

console.log( validate_url("invalidurl.com") );
// -> false

console.log( validate_url("http://validurl.com") );
// -> true
Add months to a date in Javascript
const my_date = new Date();
console.log(my_date);

// Add 3 months to today's date
new Date(my_date.setMonth(my_date.getMonth() + 3));

console.log(my_date);
Add a CSS class to element if dark mode is enabled using Javascript
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    document.getElementsByTagName("body")[0].classList.add("dark");
}
Check if dark mode is enabled using Javascript
const dark_mode_enabled = () =>
    window.matchMedia &&
    window.matchMedia("(prefers-color-scheme: dark)").matches;

console.log(dark_mode_enabled());
Methods to shuffle an array using javascript
function random_array(arr) {
    let idx = arr.length, random_num;

    while (idx != 0) {
        random_num = Math.floor(Math.random() * idx);
        idx--;

        [arr[idx], arr[random_num]] = [
            arr[random_num], arr[idx]];
    }

    return arr;
}

// Test the code
const result = random_array([10, 20, 30, 40, 50]);

console.log(result);
Remove duplicate items from array in Javascript
let numbers = [1, 3, 1, 5, 4, 3, 5];

numbers = numbers.filter(function (item, index) {
    return numbers.indexOf(item) == index;
});

console.log(numbers)
Javascript to get the number of days between two dates
const date_a = new Date("09/18/2021");
const date_b = new Date("10/20/2021");

const delta = date_b.getTime() - date_a.getTime();

const num_of_days = delta / (1000 * 60 * 60 * 24);

console.log("Number of days: " + num_of_days);
Get current timestamp in javascript
const timestamp = new Date().getTime();

console.log(timestamp);
Javascript to convert all object keys to lowercase
let person = {
    "Name": "Richard",
    "Company": "Pied Pieper",
    "Algo Name": "Compression"
};

let key, keys = Object.keys(person);
let total = keys.length;

let result = {}

while (total--) {
    key = keys[total];
    result[key.toLowerCase()] = person[key];
}

console.log(result);
Set a cookie that never expires using Javascript
document.cookie = "cookie_name=cookie_val; expires=Fri, 31 Dec 9999 21:10:10 GMT";
Set a cookie for whole domain in javascript
document.cookie = "cookie_name=cookie_value;path=/";
Count the total number of characters in a textarea while typing in javascript
const textarea = document.getElementById('textarea');
const show_counter = document.getElementById('show_counter');
const max_length = textarea.getAttribute('maxlength');

textarea.addEventListener('input', function (e) {
    const counts = this.value.length;
    show_counter.innerHTML = `${counts}/${max_length}`;
});
Javascript to run a function after script file is loaded
function load_script_file( file_url, callback ) {
  var script = document.createElement( "script" )
  script.type = "text/javascript";
  if(script.readyState) { // If browser(IE) is < 9
    script.onreadystatechange = function() {
      if ( script.readyState === "loaded" || script.readyState === "complete" ) {
        script.onreadystatechange = null;
        callback();
      }
    };
  } else {
    script.onload = function() {
      callback();
    };
  }

  script.src = file_url;
  document.getElementsByTagName( "head" )[0].appendChild( script );
}


// load script file and run the callback function 
load_script_file('script_file_path', function() {
    console.log("Script file is loaded");
});
Event System - Sigma Computing - 12/22/21
/*

We'd like to build an event system. It should have the following methods:

* on(eventName, listener) adds the listener for eventName and does not resolve the duplicates;
* off(eventName, listener) removes the listener for eventName if such combination exists;
* emit(eventName) invokes all event listeners of eventName.
* clear()

once(eventName, listener)
*/

let events = {}; // [{ listener: (){}, isOnce: boolean }]

// register the listener twice; don't need to detect if already exists
function on(eventName, listener) {
  const event = {
    listener,
    isOnce: false 
  }
  
  if (events[eventName]) {
    events[eventName].push(event); 
  } else {
    events[eventName] = [event]; 
  }
}

function off(eventName, listener) {
  if (events[eventName]) {
    events[eventName] = events[eventName].filter((registeredListenerObj) => {
      const registeredListener = registeredListenerObj.listener
      
      return registeredListener !== listener
    })
  }
  // TODO: Do we want to delete the key if there are no more listeners
}

function emit(eventName) {
  if (events[eventName]) {
    events[eventName].forEach((registeredListener) => { 
      const listener = registeredListener.listener
      const isOnce = registeredListener.isOnce
      
      listener();
      
      console.log("listener", listener)
      console.log("isOnce", isOnce)
      if (isOnce) {
        off(eventName, listener);
      }
    });
  }
}

function clear() {
  events = {};
}


function once(eventName, listener) {
  const event = {
    listener,
    isOnce: true
  };
  
  if (events[eventName]) {
    events[eventName].push(event); 
  } else {
    events[eventName] = [event]; 
  }
}



const listener = () => {
  console.log("eventName listener");
}

const secondListener = () => {
  console.log("second eventName listener");
}

// on("eventName", listener)
// on("eventName", listener)
// console.log(events)
// on("eventName", secondListener)
// console.log(events)
// on("second eventName", listener)
// console.log(events)

// emit("eventName")
// emit("second eventName")
// emit("does not exist")

// off("eventName", listener)
// console.log("off", events)
// off("eventName", listener)
// console.log("off", events)
// off("second eventName", listener)
// console.log("off", events)
// off("does not exist", listener)
// console.log("off", events)


// emit("eventName")
// emit("second eventName")

// clear()
// console.log("clear", events)
// emit()

// on("eventName", listener)
// console.log(events)

once("eventName", listener);
console.log(events)
emit("eventName")
console.log(events)
Methods to check empty array using javascript
// First method
const my_array = []

if (Array.isArray(my_array) && my_array.length) {
    //Array is not empty
} else {
    // Array is empty
}

// Second Method
if (my_array !== undefined && my_array.length > 0) {
    // Do somethong
}
Parenthesis Validation, Max Depth and Max Breadth - Braze - Full Stack - 12/20/21
// inputStr: May or may not contain paraentheses 
// valid: (()), check if valid expression
// some string // true
// (some string) // true
// ((some) string // false
// (() ())
// )))
// valid if no unbalanced set of parentheses
function hasValidParens(inputStr) {
    const parens = [];
    
    for (let i = 0; i < inputStr.split('').length; i++) {
        if (inputStr[i] === '(') {
            parens.push('(')
        } else if (inputStr[i] === ')') {
            const lastParens = parens.pop()
            if (typeof lastParens == 'undefined') {
                return false; 
            }
        }
    }
    
    return parens.length === 0; 
}


//console.log(hasValidParens("()")); // true
//console.log(hasValidParens("some string")); // true
//console.log(hasValidParens("(some string)")); // true 
//console.log(hasValidParens("((some) string")); // false 
//console.log(hasValidParens("(() ())")); // true
//console.log(hasValidParens(")))")); // false
//console.log(hasValidParens("(((")); // false


// maxDepth: (()) 2 
// ((), ()) 2
// ((), (())) 3
// Assume that it's valid 

function maxDepth(inputStr) {
    const parens = []; 
    let maxDepth = 0; 
    
    for (let i = 0; i < inputStr.split('').length; i++) {
        if (inputStr[i] === '(') {
            parens.push('(')
        } else if (inputStr[i] === ')') {
            if (parens.length > maxDepth) {
                maxDepth = parens.length;
            }
            parens.pop()
        }
    }
    
    return maxDepth;
}

//console.log(maxDepth("(())")); // 1
//console.log(maxDepth("((), ())")); // 2
//console.log(maxDepth("((), (()))")); // 2
//console.log(maxDepth("((()), ())")); // 2
// ()()(()()) // 3

// maxBreadth 

function maxBreadth(inputStr) {
    const parens = []; 
    let maxBreadth = 0; 
    
    for (let i = 0; i < inputStr.split('').length; i++) {
        if (inputStr[i] === '(') {
            parens.push('(')
        } else if (inputStr[i] === ')') {
            parens.pop();
            
            if (parens.length === 0) {
                maxBreadth++;
            }
            
        }
    }
    
    return maxBreadth;
}

console.log(maxBreadth("(())")); // 1
console.log(maxBreadth("((), ())")); // 2
console.log(maxBreadth("((), (()))")); // 2
console.log(maxBreadth("((()), ())")); // 2
console.log(maxBreadth("()()(()())")); // 3
Replace multiple spaces between words with single space using javascript
//Remove spaces along with tab spaces, new lines
const input_str = "Have   you   seen    spaces   here.";
const result_str = input_str.replace(/\s\s+/g, ' ');
console.log(result_str);
// -> Have you seen spaces here.
LRU Cache - Alphasights - Search and Discovery - Full Stack - 12/15/21
// Implement an LRU (Least recently used) cache

// Let T be the total possible page numbers that can be referred. Let N be the total number of page frames that the cache can hold at any time. The LRU caching scheme is to remove the least recently used frame when the cache is full and a new page is referenced which is not there in cache.

// Example:

// Consider the following sequential reference string, with N = 3:

// 1, 2, 3, 4, 2, 5, 1, 2, 3, 4, 5


// First we put 1,2 and then 3 into the cache. When 4 is referenced, it causes a fault since the cache is full but 4 is not in the cache. We eject 1 (the least recently used) resulting in 2, 3 and 4 in the cache. When page 2 it is in the cache, so the contents of the cache do not change. When 5 is referenced, it is not in the cache, so it causes another fault, so 3 gets ejected leading to 4, 2 and 5 being in the cache. Etc.

class lruCache {
    constructor(n) {
        this.n = n;
        this.cache = [];
        this.map = {};
    }
    
    eject(value) {
       //this.map[value] = null; 
       //this.map.remove(value);

        delete this.map[this.cache.shift()];
    }
    
    put(value) {
        if (this.map[value] != null) {
            return;
        } else {
             if (this.cache.length >= cacheSize) {
                this.eject(value);
            }
    
            this.cache.push(value);
            this.map[value] = true; 
        }
       
    }
    
    // get cache() {
    //     return this.cache;
    // }

}

const cacheSize = 3; 
// const cache = [];

// function eject() {
    
// }

// function put(value) {
//     if (cache.length >= cacheSize) {
//          eject();
//     }
    
//     cache.push(value);
// }

const input = [1, 2, 3, 4, 2, 5, 1, 2, 3, 4, 5]
function main(insertValues) {
    let cache = new lruCache(cacheSize);
    
    insertValues.forEach((insertValue) => {
        cache.put(insertValue);
        console.log(cache.cache);
        //console.log(cache.map)
    })
}

main(input);
Join array items and convert to string in javascript
const names = ["Rick", "Grimes", "Carol", "Alicia"];

//Join with default sepearor ,
name_str_1 = names.join();
console.log(name_str_1);
// -> Rick,Grimes,Carol,Alicia

//Jon with space seperator
name_str_2 = names.join(" ");
console.log(name_str_2);
// -> Rick Grimes Carol Alicia
Test every item of array against some condition in javascript
const scores = [86, 70, 56, 52, 78, 83];

const is_passed = scores.every( score => score > 33 );

console.log(is_passed);
// -> true
Convert a string to array using Array.from() in javascript
const str = "Hello";

const arr = Array.from(str);
console.log(arr);
// -> ["H","e","l","l","o"]
Search and Display Charities - Free Will - Nonprofit Gifts - Full Stack - 12/8/21
/*
  SHAPE REFERENCE

  interface Charity {
 	id: number;
 	name: string;

   // "Environment", "Education", or "Health"
 	category: string;
 	
	// if prime featureship, show amongst "Suggested" programs.
	isPrimeFeatureship: boolean;
  }

	ex:
	{
		id: 10,
		name: "Derek Zoolander Center",
		category: "Education",
		isPrimeFeatureship: true
	}
*/

/**
	Given a list of charities, return items to display in grid.
	
	Criteria:
	- Should match the header's selected category; "Suggested" shows prime featureships.
	- Should narrow results with the search, case insensitive.
	- Should sort alphabetically.

	params:
	charities: Charity[] - list of all charities
	activeCategory: string - the selected category
	searchString: string - the entered search string
*/
function getGridItems(charities, activeCategory, searchString) {
	console.log('searchStrin ', searchString)
	let filterFunction; 
	switch (activeCategory) {
		case "Suggested":
			filterFunction = (charity) => {
				return charity.isPrimeFeatureship
			}
			break;
		default: 
			filterFunction = (charity) => {
				return activeCategory == charity.category
			}
			break;
	}
	
	const filterCharities = charities.filter(filterFunction)
	const filteredSearchCharities = filterCharities.filter((charity) => {
		return charity.name.toLowerCase().includes(searchString.toLowerCase());
	})
	
	console.log('filteredSearchCharities', filteredSearchCharities)
	const sortedCharities = filteredSearchCharities.sort((charity1, charity2) => {
		if (charity1.name < charity2.name) {
			return -1;
		} else if (charity1.name < charity2.name) {
			return 1; 
		}
		return 0;
		// return charity1.name - charity2.name; 
	});
	// console.log('filterCharities', filterCharities)

	// placeholder for visualization
	return sortedCharities;
}

// charities from server. consider this synchronous.
const allCharities = getSeedCharities();

const CharityView = () => {
	// [value, setValue(new_value)] = React.useState(initial_value)
	const [activeCategory, setActiveCategory] = React.useState("Suggested");
	const [searchString, setSearchString] = React.useState("");

	const gridItems = getGridItems(allCharities, activeCategory, searchString);

	return (
		<div className="main">
			<Header />
			<CharityGridControls
				activeCategory={activeCategory}
				setActiveCategory={setActiveCategory}
				searchString={searchString}
				setSearchString={setSearchString}
			/>
			<CharityGridBody
				charities={gridItems}
				activeCategory={activeCategory}
				// carousel only, ignore
				onLeftClick={null}
				onRightClick={null}
			/>
		</div>
	);
};

/**
	-- IGNORE THIS -- 
	
	Part Two: Parent / Child programs
	
	Let's introduce two additional properties to the Charity shape.
	
	The first will be included and pre-filled in the server response:
	
	----
	parentProgramId: number
	----
	
	This property indicates the parent program of the child program.
	(ex 'Columbia University' is the parent program of 'Columbia School of Music')
	
	Only child programs will have this property defined.
	The parentProgramId will match the id of the parent charity.
	
	Ex:
	PARENT
	{
		(...)
		id: 10,
	}

	CHILD
	{
		(...)
		id: 11,
		parentProgramId: 10,
	}
	
	
	The second new property is:
	
	----
	childProgramCount: number
	----
	
	This indicates the number of child programs a program has.
	
	ex:
	{
		(...)
		id: 10,
		childProgramCount: 1,
	}
	
	This is NOT provided in the server response. Instead, modify your result from part 1 to:
	
	1. implement this childProgram count
	2. hide all child programs from the grid
	
*/

/**
	-- IGNORE THIS --
	
	Implement the carousel view.
	
	Requirements:
	
	- Shows up to 3 programs at a time.
	
	- Clicking a left/right control "skips" to a new set of 3 programs
	
	- The carousel should jump from the front to the back of the array if the user hits "left" from the first set, and vice versa for hitting "right" from the end.
		
		ex: 1, 2, 3 [LEFT] 13, 14, 15
		ex: 25, 26 [RIGHT] 1, 2, 3 
	
	<CharityGridBody /> above has two callback props for their respective arrows:
	
	onLeftClick
	onRightClick
*/
Microsoft Fill Paint - Bloomberg - Port Interactive Analytics - Full Stack - 12/6/21
// Start typing here

// image: 2d array iof numbers, grayscale 0 - 10 
// blank canvas, fills whole canvas
// function floodfill(image, xy, xz, tc)
// BFS, DFS to search 
// Add nodes/coordinates arounda  pixel (edge case)
// 0 0 0
// 1 1 0 // This shouldn't get filled 
// 0 0 1
//
/**
 * 0 0 0 0 0
   1 1 1 0 0
   0 0 0 1 0
   1 1 1 1 0
   0 0 0 0 0
   
   (1,2) --> (1,2), (0,2), (2,2)
   
   0 0 0 0 0
   1 1 1 0 0
   3 3 3 1 0
   1 1 1 1 0
   0 0 0 0 0
 * 
*/
Flexible UI Component - Bloomberg - Asset Management AIM - Full Stack - 12/6/21
// Start typing here

customers, not predefined properties 
properties displayed - for their customers 
all text based properties 
all properties are displayed the same way 
support different retailers - generic data store 

API to save the properties 
GET
update v. create v. PUT replacement
DELETE
security: Authorization Headers

merchant 
type of merchandise 

{
    retailer_id: 343,
    
    properties: [
        {
            itemType: id, 
            properties: {}
        }
    ]
        "type": { // id of type 
            "key": "value",
            "": {
            }
        }
    }
} 

// data storage 
merchants table (id, name)
itemTypes (id, name)
properties table (itemType - id, key, value)
Valid Dictonary String - Bloomberg - Port Interactive Analytics - Full Stack - 11/8/21
// Start typing here// Start typing here

// Given an input of a dictionary of words and an input string that does not contain spaces, write a method that returns a string with spaces inserted accordingly.

Input: "bloombergisfun", ["bloom","bloomberg","is","fun"]
Output: "bloomberg is fun"

// Returns the shorter matching string
"bloombergisfun", ["bloom",  "bloomberg","is","fun"]
"bloom berg is fun"

function spacedString(str, dictionary) {
    let currentStr = ''
    let words = [];
    
    for(let i = 0; i < str.length; i++) {
        currentStr ++ str[0]
        
        if (dictionary.has(currentStr)) {
            words.push(currentStr);
            currentStr = '';
        } 
    }
    
    return words.join(' ');
}
Sort Tree - Bloomberg - Port Interactive Analytics - Front End - 12/6/21
// Let's assume you are given the world tree, wherein the first level represents continents, the second level represents countries, the third level represents states/provinces and so on. Write a method to re-arrange this tree in such a way that all children of every node are sorted in alphabetical order.
     World
    / 
  North America
    /                        \
    US                       Canada
    /     \       \ 
California  NYC  Alabama

Node {
    value
    children: Node[]
}

Tree {
 topNode: Node
}

function sortChildren(tree) {


    // Continents 
    tree.topNode.children.sort((childNode1, childNode2) => {
        if (childNode1.value < childNode2.value) {
            return -1;
        } else (childNode1.value > childNode2.value) {
            return 1; 
        }
        return 0;
    })
    
    tree.topNode.children.foreach((continent) => {
        continent.children.foreach((country) => {
            country.children.foreach((state) => {
                
            })
        })
    });
}

function sort(node) {
    if (node.children) {
        node.children.foreach(() => { sort(node)}))
    } else {
        // reached the end 
    }
}
Batched Requests - AirTable - Automations - Front End - 12/3/21
/**
GET /read?keys=foo,bar

Response:
{
    "foo": 12,
    "bar": 42
}

Implement a function getKey(key) which fetches the specified key
and returns its value asynchronously to the caller.

The function signature is a starting point. Feel free to wrap it
in a class or add additional arguments if needed.

Desired behavior:
If getKey is called multiple times in a small window of time,
there should be a single network request to fetch all the required
values. For example, if the below 3 calls happen within a small window
of time, there should be a single network request:

getKey('foo', cb)
getKey('bar')
getKey('foo')
*/

const keys = new Set();
const keysToCallback = [];
let isFirstCall = true; 

function getKey(key, callback: (data: number) => void) {
    keys.add(key);
    keysToCallback.push({
        key, callback
    }); 
    //const keyPromise = new Promise();
    
    if (isFirstCall) {
        setTimeout(() => {
            $.ajax({
                path: '/read?keys=' + [...keys].join(',')
            }).then((values) => {
                //keyPromise.resolve(keysAndValues);    
                // Object.keys
                keysToCallback.foreach((value) => {
                    [key, callback] = value
                    callback(values[key])
                })
            }, () => {
                // Log 
                 
            });
            isFirstCall = true; 
        }, 1000);
        
        isFirstCall = false;
    }
    
    // keyPromise.then((values) => {
    //     return values[key];
    // });
}
Name Matching - Checkr - Adjudication - Full Stack - 11/19/21
/******************
 * Name Matching
 *
 *   At Checkr, one of the most important aspects of our work is accurately matching records
 * to candidates. One of the ways that we do this is by comparing the name on a given record
 * to a list of known aliases for the candidate. In this exercise, we will implement a
 * `nameMatch` method that accepts the list of known aliases as well as the name returned
 * on a record. It should return true if the name matches any of the aliases and false otherwise.
 *
 * The nameMatch method will be required to pass the following tests:
 *
 * 1. Exact match
 *
 *   knownAliases = ["Alphonse Gabriel Capone", "Al Capone"]
 *   nameMatch(knownAliases, "Alphonse Gabriel Capone") => true
 *   nameMatch(knownAliases, "Al Capone")               => true
 *   nameMatch(knownAliases, "Alphonse Francis Capone") => false
 *
 *
 * 2. Middle name missing (on alias)
 *
 *   knownAliases = ["Alphonse Capone"]
 *   nameMatch(knownAliases, "Alphonse Gabriel Capone") => true
 *   nameMatch(knownAliases, "Alphonse Francis Capone") => true
 *   nameMatch(knownAliases, "Alexander Capone")        => false
 *
 *
 * 3. Middle name missing (on record name)
 *
 *   knownAliases = ["Alphonse Gabriel Capone"]
 *   nameMatch(knownAliases, "Alphonse Capone")         => true
 *   nameMatch(knownAliases, "Alphonse Francis Capone") => false
 *   nameMatch(knownAliases, "Alexander Capone")        => false
 *
 *
 * 4. More middle name tests
 *    These serve as a sanity check of your implementation of cases 2 and 3
 *
 *   knownAliases = ["Alphonse Gabriel Capone", "Alphonse Francis Capone"]
 *   nameMatch(knownAliases, "Alphonse Gabriel Capone") => true
 *   nameMatch(knownAliases, "Alphonse Francis Capone") => true
 *   nameMatch(knownAliases, "Alphonse Edward Capone")  => false
 *
 *
 * 5. Middle initial matches middle name
 *
 *   knownAliases = ["Alphonse Gabriel Capone", "Alphonse F Capone"]
 *   nameMatch(knownAliases, "Alphonse G Capone")       => true
 *   nameMatch(knownAliases, "Alphonse Francis Capone") => true
 *   nameMatch(knownAliases, "Alphonse E Capone")       => false
 *   nameMatch(knownAliases, "Alphonse Edward Capone")  => false
 *   nameMatch(knownAliases, "Alphonse Gregory Capone") => false
 *
 *
 * Bonus: Transposition
 *
 * Transposition (swapping) of the first name and middle name is relatively common.
 * In order to accurately match the name returned from a record we should take this
 * into account.
 *
 * All of the test cases implemented previously also apply to the transposed name.
 *
 *
 * 6. First name and middle name can be transposed
 *
 *   "Gabriel Alphonse Capone" is a valid transposition of "Alphonse Gabriel Capone"
 *
 *   knownAliases = ["Alphonse Gabriel Capone"]
 *   nameMatch(knownAliases, "Gabriel Alphonse Capone") => true
 *   nameMatch(knownAliases, "Gabriel A Capone")        => true
 *   nameMatch(knownAliases, "Gabriel Capone")          => true
 *   nameMatch(knownAliases, "Gabriel Francis Capone")  => false
 *
 *
 * 7. Last name cannot be transposed
 *
 *   "Alphonse Capone Gabriel" is NOT a valid transposition of "Alphonse Gabriel Capone"
 *   "Capone Alphonse Gabriel" is NOT a valid transposition of "Alphonse Gabriel Capone"
 *
 *   knownAliases = ["Alphonse Gabriel Capone"]
 *   nameMatch(knownAliases, "Alphonse Capone Gabriel") => false
 *   nameMatch(knownAliases, "Capone Alphonse Gabriel") => false
 *   nameMatch(knownAliases, "Capone Gabriel")          => false
 */

function hasMiddleName(name) {
  let splitName = name.split(' ');
  
  return splitName.length === 3;
}

function nameWithoutMiddleName(name) {
  if (hasMiddleName(name) {
    return [splitName[0], splitName[2]].join(' ');
  } 

  return name
}


function nameWithMiddleInitial(name) {  
  if (hasMiddleName(name) {
    return [splitName[0], splitName[1][0], splitName[2]].join(' ');
  } else {
    return name
  }
}

function nameMatch(knownAliases, name) {
  // Implement me
  let hasExactMatch = knownAliases.includes(name);
  
  if (hasExactMatch) {
    return hasExactMatch;
  }
  
  // Find a match with the middle name missing on the provided name
  let hasFuzzyMiddleNameMatch = knownAliases.includes(nameWithoutMiddleName(name));
  if (hasFuzzyMiddleNameMatch) {
    return hasFuzzyMiddleNameMatch;
  }

  // Find a match with the middle name missing on the provided aliases
  let aliasWithoutMiddleName = knownAliases.map((alias) => nameWithoutMiddleName(alias))
  let hasFuzzyAliasMiddleNameMatch = aliasWithoutMiddleName.includes(name);
  if (hasFuzzyAliasMiddleNameMatch) {
    return hasFuzzyAliasMiddleNameMatch;
  }


  let hasMiddleInitialMatch = knownAliases.includes(nameWithMiddleInitial(name));
   if (hasMiddleInitialMatch) {
    return hasMiddleInitialMatch;
  }


  let aliaswithMiddleInitialName = knownAliases.map((alias) => nameWithMiddleInitial(alias))
  let hasAliasMiddleInitialNameMatch = aliaswithMiddleInitialName.includes(name);

  if (hasAliasMiddleInitialNameMatch) {
    return hasAliasMiddleInitialNameMatch;
  }
    
  
  return false;
}

/** Tests **/

function assertEqual(expected, result, errorMessage) {
  if (result !== expected) {
    console.log(errorMessage);
    console.log(`expected: ${expected}`);
    console.log(`actual: ${result}`);
    console.log('');
  }
}

function test() {
  let knownAliases;

  knownAliases = ["Alphonse Gabriel Capone", "Al Capone"];
  assertEqual(true,  nameMatch(knownAliases, "Alphonse Gabriel Capone"), "error 1.1");
  assertEqual(true,  nameMatch(knownAliases, "Al Capone"),               "error 1.2");
  assertEqual(false, nameMatch(knownAliases, "Alphonse Francis Capone"), "error 1.3");

  knownAliases = ["Alphonse Capone"];
  assertEqual(true,  nameMatch(knownAliases, "Alphonse Gabriel Capone"), "error 2.1");
  assertEqual(true,  nameMatch(knownAliases, "Alphonse Francis Capone"), "error 2.2");
  assertEqual(false, nameMatch(knownAliases, "Alexander Capone"),        "error 2.3");

  knownAliases = ["Alphonse Gabriel Capone"];
  assertEqual(true,  nameMatch(knownAliases, "Alphonse Capone"),         "error 3.1");
  assertEqual(false, nameMatch(knownAliases, "Alphonse Francis Capone"), "error 3.2");
  assertEqual(false, nameMatch(knownAliases, "Alphonse Edward Capone"),  "error 3.3");

  knownAliases = ["Alphonse Gabriel Capone", "Alphonse Francis Capone"];
  assertEqual(true,  nameMatch(knownAliases, "Alphonse Gabriel Capone"), "error 4.1");
  assertEqual(true,  nameMatch(knownAliases, "Alphonse Francis Capone"), "error 4.2");
  assertEqual(false, nameMatch(knownAliases, "Alphonse Edward Capone"),  "error 4.3");

  knownAliases = ["Alphonse Gabriel Capone", "Alphonse F Capone"];
  assertEqual(true,  nameMatch(knownAliases, "Alphonse G Capone"),       "error 5.1");
  assertEqual(true,  nameMatch(knownAliases, "Alphonse Francis Capone"), "error 5.2");
  assertEqual(false, nameMatch(knownAliases, "Alphonse E Capone"),       "error 5.3");
  assertEqual(false, nameMatch(knownAliases, "Alphonse Edward Capone"),  "error 5.4");
  assertEqual(false, nameMatch(knownAliases, "Alphonse Gregory Capone"), "error 5.5");

  knownAliases = ["Alphonse Gabriel Capone"];
  assertEqual(true,  nameMatch(knownAliases, "Gabriel Alphonse Capone"), "error 6.1");
  assertEqual(true,  nameMatch(knownAliases, "Gabriel A Capone"),        "error 6.2");
  assertEqual(true,  nameMatch(knownAliases, "Gabriel Capone"),          "error 6.3");
  assertEqual(false, nameMatch(knownAliases, "Gabriel Francis Capone"),  "error 6.4");

  knownAliases = ["Alphonse Gabriel Capone"];
  assertEqual(false, nameMatch(knownAliases, "Alphonse Capone Gabriel"), "error 7.1");
  assertEqual(false, nameMatch(knownAliases, "Capone Alphonse Gabriel"), "error 7.2");
  assertEqual(false, nameMatch(knownAliases, "Capone Gabriel"),          "error 7.3");

  console.log('Test run finished')
}
test();
War - Affirm - Asset Management AIM - 11/18/21
/*
Part 1:

 * this is a two player card game
 * the game starts with a deck of 52 cards represented as
   unique integers [1...52]
 * the cards are randomly shuffled and then dealt out to both players evenly.
 * on each turn:
     * both players turn over their top-most card
     * the player with the higher valued card takes
       the cards and puts them in their win pile
       (scoring 1 point per card)
 * this continues until all the players have no cards left
 * the player with the highest score (number of cards in their win pile) wins.
    * if they have the same number of cards in their win pile, tiebreaker goes to the player with the highest card in their win pile.

Be able to play the game with N players.
An input to the game will now be a list of strings (of length N) indicating the player names.
The deck contains M cards of distinct integers.
It is not guaranteed M % N == 0. If there are leftover cards they should randomly be handed out to remaining players.
i.e. with 17 cards and 5 people: 2 people get 4 cards and 3 get 3 cards
For example the input: game(["Joe", "Jill", "Bob"], 5) would be a game between 3 players and 5 cards.
you should print the name of the player that won the game.
*/

process.stdin.resume();
process.stdin.setEncoding("ascii");
var input = "";
process.stdin.on("data", function (chunk) {
    input += chunk;
});
process.stdin.on("end", function () {
    // now we can read/parse input
    
    const shuffleArray = array => {
        for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            const temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
    }
    
    let shuffledDeck = Array.from({length: 52}, (_, i) => i + 1);
    shuffleArray(shuffledDeck);
    
    shuffleArray(shuffledDeck);
    console.log('shuffledDeck', shuffledDeck);
    
    let player1Deck = shuffledDeck.slice(0, 26);
    let player2Deck = shuffledDeck.slice(27);
    
    console.log('player1Deck', player1Deck);
    console.log('player2Deck', player2Deck);

    let player1WinningDeck = [];
    let player2WinningDeck = [];

    while (player1Deck.length > 0 || player2Deck.length > 0) {
        let player1CurrentCard = player1Deck.pop();
        let player2CurrrentCard = player2Deck.pop();
        
        if (player1CurrentCard > player2CurrrentCard) {
            player1WinningDeck.push(player1CurrentCard);
            player1WinningDeck.push(player2CurrrentCard);
        } else {
            player2WinningDeck.push(player1CurrentCard);
            player2WinningDeck.push(player2CurrrentCard);
        }
    }

    if (player1WinningDeck.length > player2WinningDeck.length) {
        console.log('player 1 won with ' + player1WinningDeck.length + ' points');
    } else if (player1WinningDeck.length < player2WinningDeck.length) {
        console.log('player 2 won with ' + player2WinningDeck.length + ' points');
    } else { 
        let sortedPlayer1WinningDeck = player1WinningDeck.sort();
        let sortedPlayer2WinningDeck = player2WinningDeck.sort();
        
        let player1MaxCard = sortedPlayer1WinningDeck[sortedPlayer1WinningDeck.length - 1]
        let player2MaxCard = sortedPlayer2WinningDeck[sortedPlayer2WinningDeck.length - 1]
        if (player1MaxCard > player2MaxCard) {
            console.log('player 1 won with ' + player1WinningDeck.length + ' points with max card ' + player1MaxCard);
        } else {
            console.log('player 2 won with ' + player2WinningDeck.length + ' points with max card ' + player2MaxCard);
        }
    }
    
    function war(players, numCards) {
        let playerDecks = {};
        let winningDecks = {};
        
        let shuffledDeck = Array.from({length: numCards}, (_, i) => i + 1);
        shuffleArray(shuffledDeck);
        
        // shuffledDeck.length / player.length 
        
        players.map((player) => {
            playerDecks[player] = [];
            winningDecks[player] = [];
        });
        
        for (let i = 0; i < shuffledDeck.length; i++) {
            let playerIndex = i % player.length 
            
            playerDecks[players[playerIndex]].push(card);
        }
        
        
        let hasCard s = true
        
        while (playerDecks.length) {
            let playingCards = [];
            
            for (const [player, playerDeck] of Object.entries(playerDecks)) {
                if (playerDeck.length == 0) {
                    delete playerDecks.player
                }
                
                playingCards.push({
                    player: player,
                    card: playerDeck.pop()
                });
            }
            
            let sortedPlayingCards = playingCards.sort((firstEl, secondEl) => { firstEl.card - secondEl.card } )
            let winningCard = sortedPlayingCards[playingCards.length]
            
            winningDecks[winningCard.player] = playerDecks[winningCard.player].concat(playingCards.map(playingCard => playingCard.card));
        }
        
        
        
        let arrWinning = []
        for (const [player, playerDeck] of Object.entries(winningDecks)) {
            arrWinning.push({
                player: player, 
                deckLength: playerDeck.length
            })
        }
        
        
        arrWinning.sort((firstEl, secondEl) => { firstEl.deckLength - secondEl.deckLength } )
        let tiedWinners = arrWinning.reduce( (tiedWinners, arrWinner) => 
            if (arrWinner.deckLength == arrWinning[arrWinning.length.deckLength) {
                tiedWinners.push(arrWinner);
            }
        }, []);
        
        
        if (tiedWinners.length == 1) {
            
        } else {
            tiedWinners.map((tiedWinner) => {
                winningDecks[tiedWinner.player].sort()
            })
            winningCards = tiedWinners.reduce((winningCard, tiedWinner) => {
                winningDecks.length
                winningDecks[tiedWinner.player][winningDecks.length - 1]
            }, []).sort()
            winningCards[winningCards.length]
            
        }
        
        
    }
});
Array.find() - get the very first element satisfy a condition Javascript
const numbers = [50, 60, 70, 80];
const element = numbers.find(num => num > 50);
console.log(element);
// -> 60
Difference in Gift Values - Free Will - Nonprofit Gifts - Full Stack - 11/15/21
// Input:
//
// estateSize - the total value of a person's estate (similar to 'net worth')
// oldGifts - list of existing gifts a person is donating to charity
// newGifts - list of new/updated gifts a person is donating to charity
//
// {
//    nonProfit: string,
//    amount: number,
//    amountType: 'dollar' | 'percent'
// }
//
// Instructions:
//
// 1. Calculate the difference in total value between the new and old gifts in dollars
// New and old gift difference example:
// Old gift: 150
// New gift: 100
// Expected output: -50
//
// Part 1 expected output: -19500
//
// 2. Return the difference in total value between the new and old gifts by non-profit
//
// Expected output:
// {
//     'Planned Parenthood': 1000,
//     'Doctors Without Borders': -500,
//     'United Way': -50000,
//     'Red Cross': 30000
// }

const estateSize = 1000000;

const oldGifts = [
  {
    nonProfit: "Planned Parenthood",
    amount: 10,
    amountType: "percent",
  },
  {
    nonProfit: "Doctors Without Borders",
    amount: 1000,
    amountType: "dollar",
  },
  {
    nonProfit: "United Way",
    amount: 5,
    amountType: "percent",
  }];

const newGifts = [
  {
    nonProfit: "Planned Parenthood",
    amount: 10,
    amountType: "percent",
  },
  {
    nonProfit: "Planned Parenthood",
    amount: 1000,
    amountType: "dollar",
  },
  {
    nonProfit: "Doctors Without Borders",
    amount: 500,
    amountType: "dollar",
  },
  {
    nonProfit: "Red Cross",
    amount: 3,
    amountType: "percent",
  }];

function giftTotal(estateSize, gifts) {
  let giftTotal = 0;
  for (let i = 0; i < gifts.length; i++) {
    if (gifts[i].amountType == 'dollar') {
      giftTotal += gifts[i].amount;
    } else {
      giftTotal += (gifts[i].amount / 100) * estateSize;
    }
  }

  return giftTotal;
}

function calculateTotalDiff(estateSize, oldGifts, newGifts) {
  //todo
  let oldGiftTotal = giftTotal(estateSize, oldGifts);
  let newGiftTotal = giftTotal(estateSize, newGifts);

  return newGiftTotal - oldGiftTotal;
}

function total(estateSize, gift) {
  if (gift.amountType == 'dollar') {
    return gift.amount;
  } else {
    return (gift.amount / 100) * estateSize;
  }
}

function calculateDiffByNonProfit(estateSize, oldGifts, newGifts) {
  //todo
  let nonProfitToDiff = newGifts.reduce((nonProfitToDiff, newGift) => {
    let nonProfitCurrentTotal = nonProfitToDiff[newGift.nonProfit];
    if (nonProfitToDiff[newGift.nonProfit] != null) {
      nonProfitToDiff[newGift.nonProfit] += total(estateSize, newGift);
    } else {
      nonProfitToDiff[newGift.nonProfit] = total(estateSize, newGift);
    }

    return nonProfitToDiff;
  }, {});

  // return oldGifts.reduce((nonProfitToDiff, oldGift) => {
  //   let nonProfitCurrentTotal = nonProfitToDiff[oldGift.nonProfit];

  //   if (nonProfitToDiff[oldGift.nonProfit] != null) {
  //     nonProfitToDiff[oldGift.nonProfit] -= total(estateSize, oldGift);
  //   } else {
  //     nonProfitToDiff[oldGift.nonProfit] = -total(estateSize, oldGift);
  //   }
  // }, nonProfitToDiff);

  oldGifts.forEach((oldGift) => {
    let nonProfitCurrentTotal = nonProfitToDiff[oldGift.nonProfit];

    if (nonProfitToDiff[oldGift.nonProfit] != null) {
      nonProfitToDiff[oldGift.nonProfit] -= total(estateSize, oldGift);
    } else {
      nonProfitToDiff[oldGift.nonProfit] = -total(estateSize, oldGift);
    }
  })

  return nonProfitToDiff;
}

calculateTotalDiff(estateSize, oldGifts, newGifts);
calculateDiffByNonProfit(estateSize, oldGifts, newGifts);
Recommendations - Bloomberg - Port Interactive Analytics - Full Stack - 11/8/21
- Build a recommendation system
- Given the likes of users, and a list of a user's likes, give recommendations 
1 A B C D
2 DC D 
3 C D

likes: B C

Returns [D, A] in this specific order (because D has two likes, and A only has one)


function reccomendations(dataSet: string[][], likes: string[])
  // hashmap D: 2, A: 1
  let currentRecommendations = {};
  loop over data set to get each individual user's likes 
    let isMatch = true;
    let currentReccomendations= []
    loop over each individuals likes 
      if data set user like is in likes
        matches++
      else isMatch = false
    if (matches == likes.length) 
     // Found a user match 
     add diff of user matches (e.g. reccomendations to currentRecommendations)

  // return currentRecommendations as a an array in sorted order
Compressed String with Sort - C3 AI - CRM - Full Stack - 11/11/21
function compressedStr(input) {
  let compressedResult = input[0];
  let currentChar = input[0]
  let currentCount = 1
 
  for (let i = 1; i < input.length; i++) {
    if (currentChar == input[i]) {
      currentCount++;
    } else {
      compressedResult += currentCount;
      compressedResult += input[i];
 
      currentChar = input[i];
      currentCount = 1; 
    }
  }
 
  compressedResult += currentCount;
 
  return compressedResult;
}
 
console.log(compressedStr('aaaaaaaaaabbbbbjjjkklaa'));
 
function compressedSort(input) {
  let arr = []
  //[(a, 10), (b,5)] { char: 'a', count: '1'0 } 
  let currentChar = input[0];
  for (let i = 1; i < input.length; i++) {
    if (isCharacterALetter(input[i])) {
      
    } else {
      // Digit 
      
    }
  }
}
 
 
function isCharacterALetter(char) {
  return (/[a-zA-Z]/).test(char)
}
2D Array Path - C3 AI - CRM - Full Stack - 11/11/21
/*
You are given an NxN map where each cell consists of a non-negative integer value 
representing the height of the cell.
 
There is a player on the map that stands at the top-left cell. 
The player wants to get to the bottom-right cell. 
The player can only move up, down, left, or right. 
Also, the player can move between two cells if the absolute difference in height between them is less or equal to the player jump power.
 
Given a map and a player jump power, 
write a function that returns true if the player can reach the bottom right cell, 
or false otherwise.
 
0 1 1 3 4
3 4 2 0 1
2 2 2 4 3
1 3 4 3 1
1 2 1 1 0
 
jump Power = 3
0 1 1
    2
    2
    4
    1 1 0
    
jump power = 1
0 1 2
    2
2 2 2
1
1 2 1 1 0
 
*/

function hasPath(map, jumpPower) {
  let queue = [{
    x: 0,
    y: 0
  }]
  
  let visited = {};
               
  while (!queue.empty) {
    let position = queue.pop
    
    if (visited[(position.x, position.y]) {
      continue; 
    } else {
      if (position.y == map.length && position.x == map[0].length) {
      // reached the bottom right 
      return true;
    } else {
      let right = map[position.y][position.x + 1]
      
      let left = map[position.y][position.x - 1]
      
      if (position.y + 1 < map.length) {
        let bottom = map[position.y + 1][position.x]
        if (jumpPower + map[position.x][position.y] >= bottom) {
          queue.push({
            x: postion.x,
            y: position.y + 1
          });
        }
      }
      
      let top = map[position.y - 1][position.x]
      
      visited[(position.x, position.y)] = true
    }
    
    //if (map[positon.x][position.y])
  }
  
  return false; 
}
Reusable Components
import React  from "react";

const InputField = ({ value, label, name, placeholder, type, onChange }) => (
  <div className="form-group">
    {label && <label htmlFor="input-field">{label}</label>}
    <input
      type={type}
      value={value}
      name={name}
      className="form-control"
      placeholder={placeholder}
      onChange={onChange}
    />
  </div>
);

export default InputField;




import React, { useState } from "react";
import InputField from "../UI/InputField";

const AddProductForm = () => {
  const [inputValue, setInputValue] = useState({ name: "", price: "" });
  const { name, price } = inputValue;

  const handleChange = (e) => {
    const { name, value } = e.target;
    setInputValue((prev) => ({
      ...prev,
      [name]: value,
    }));
    console.log(inputValue);
  };

  return (
     <Form>
       <InputField
         type="text"
         value={name}
         placeholder="Product Name"
         label="Name"
         name="name"
         onChange={handleChange}
       />
       <InputField
         type="number"
         value={price}
         placeholder="Add Price"
         label="Price"
         name="price"
         onChange={handleChange}
       />
       <Button color="primary">Add</Button>{" "}
       <Button color="secondary">Cancel</Button>
     </Form>
  );
};

export default AddProductForm;
Array iteration with setTimeout() javascript
const persons = ['John', 'Rick', ' Carol'];

let delay = 0;
persons.forEach(function (person) {
    setTimeout(function () {
        console.log(person);
    }, 1000 + delay);
    delay += 1000;
});
Van Ecks Sequence - Bloomberg - Asset Management AIM - Full Stack - 11/5/21
// Van Eck is a sequence that has 3 properties:
//   - Starts with 0
//   - For each element, count the number of steps since it's last appeared. This number of steps becomes the next term
//   - If the element has not appeared before, the next term is 0

// Sequence: [0, 0, 1, 0, 2, 0, 2, 2, 1, 6, 0, 5, ...]
//           [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// Problem: Given an index, define a function that returns the element in Van Eck's sequence at that index.

function vanEcksAtIndex(index) {
    let arr = [0];
    // Last index which the number as appeared 
    let lastAppeared = {0: 0};
    
    
    for (let i = 0; i < index; i++) {
        console.log('i', i)
        console.log('arr', arr)
        console.log('lastAppeared', lastAppeared)
        if (lastAppeared[arr[i]] != null) {
            // Element has appeared before
            arr.push(i - lastAppeared[arr[i]]);
        } else {
            // Element hasn't appeared before
            arr.push(0);
        }
        lastAppeared[arr[i]] = i;
    }
    
    return arr[index];
}

// arr = [0], lastAppeared = { 0: 0 }
// i = 0, arr = [0, 0], lastAppeared = { 0: 0 }
// i = 1, arr = [0, 0, 1], lastAppeared = { 0: 1 }

console.log(vanEcksAtIndex(9));
Javascript code to remove falsy value like null, undefined, false from array
const my_array = [10, false, null, "devsheet", undefined];
const filtered_array = my_array.filter(Boolean);
// -> [10,"devsheet"]
Real time text-to-speech converter using Javascript
var speech = new SpeechSynthesisUtterance();
var all_voices = speechSynthesis.getVoices();

speech.voice = all_voices[1];
speech.text = "Hello John. Welcome to Devsheet";

speechSynthesis.speak(speech);
Stop loop for some seconds in Javascript
//Using recursion function
var counter = 0;

function loop_func() {
    setTimeout(function () {
        console.log('Loop Iteration: ' + counter);
        if (counter < 4) {
            loop_func();
        }
        counter++;
    }, 2000); //Add delay here - 2000 = 2 seconds
}

// The loop will run 5 times
loop_func();
Get the day name from given date in Javascript
const date_str = "07/20/2021";
const date = new Date(date_str);
const full_day_name = date.toLocaleDateString('default', { weekday: 'long' });
// -> to get full day name e.g. Tuesday

const short_day_name = date.toLocaleDateString('default', { weekday: 'short' });
console.log(short_day_name);
// -> TO get the short day name e.g. Tue
Get year from given date using Javascript
const date = "2018-04-05";
const date_obj = new Date(date);
const year = date_obj.getFullYear();
// -> 2018

// OR The above code can be written in single line
new Date("2018-04-05").getFullYear()
// -> 2018
Get current year using Javascript Date getFullYear() method
const today_date = new Date();
const current_year = today_date.getFullYear();
// -> returns the current year
Check whether a checkbox is checked or not using Javascript only
var checkbox = document.getElementById("checkbox_id");

if (checkbox.checked) {
    console.log("Checkbox is checked");
} else {
    console.log("Checkbox is not checked");
}
Get month name from a date using javascript
const date_str = "2021-09-20";
const my_date = new Date(date_str);

//Get month name from date using .toLocaleString() method
const full_month_name = my_date.toLocaleString("default", { month: "long" });
// -> September

//Get month name from date using .getMonth() method
const month_names = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const month_num = my_date.getMonth();
const month_name = month_names[month_num];
// -> September
Get the current month name using javascript
var today_date = new Date();

// Using toLocaleString(Ecmascript)
// Full month name
const full_month_name = today_date.toLocaleString('default', { month: 'long' });
console.log(full_month_name);
// -> October(Or the current month)

//Short month name
const short_month_name = today_date.toLocaleString('default', { month: 'short' });
console.log(short_month_name);
// -> Oct (Or the short version of current month)

//Using getMonth() method
const month_num = today_date.getMonth();
const all_months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const current_month = all_months[month_num];
console.log(current_month);
// -> October (Or the curent month name)
Bind external value inside .map javascript
setFornecedorValue(){
    return this.userContext.getFornecedor().cnpjCpf; 
  }

  montarPedidos = (pedidos: any) => {
    const self = this;

    return pedidos.map(function (item: any) {  
      return {...item, cnpjFornecedor: self.setFornecedorValue() }; 
    });
  }

  montarPedidos(arrayValues);
Remove duplicates ids from object array
score = [
    {
        id:123,
        name:"Arun",
        point:"10"
    },
    {
        id:123,
        name:"Arun",
        point:"10"
    },
    {
        id:12233,
        name:"Arudfn",
        point:"11230"
    },
]


const unique_result = [...new Map(score.map((item) => [item['id'], item])).values()]
Assign items of arrays to multiple variable when creating it (Array Destructuring) Javascript(ES6)
//First code example
const [value_1, value_2, value_3] = ["item_1", "item_2", "item_3"]
console.log(value_1);
console.log(value_2);
console.log(value_3);

//Second code example
const [fruits, vegetables] = [
    [{"name": "Orange"}, {"name": "Grapes"}, {"name": "Banana"}],
    [{ "name": "Potato" }, { "name": "Onion" }, { "name": "Lady fingers" }]
];
console.log(fruits);
console.log(vegetables);
Check if given value is an array in Javascript
const arr = ['1', '2', '3'];
const str = 'Devsheet';

is_array = Array.isArray(arr);
console.log(is_array);

is_array = Array.isArray(str);
console.log(is_array);
Filter array
const list = [1,2,3,4,5]

const even_list = list.filter((accumulator,element)=>{
    return element % 2 == 0
})
How to Remove duplicate elements from array in JavaScript ?
//Method 1
// Defining a set of the cities
  let city = [
    "surat",
    "ahmedabad",
    "rajkot",
    "mumbai",
    "surat",
    "delhi",
    "ahmedabad",
    "anand",
  ];
  
  // For removing the duplicate values
  // we are using the Set() function
  let unique_city = [new Set(city)];
  
  // Printing the unique cities
  console.log(unique_city);

  //Output
  ["surat", "ahmedabad", "rajkot", "mumbai", "delhi"]

//Method 2

// Defining the unique cities from the above
  // array by using forEach loop
  let unique_city = [];
  city.forEach((c) => {
    if (!unique_city.includes(c)) {
      unique_city.push(c);
    }
  });
  console.log(unique_city);

  //Output
  ["surat", "ahmedabad", "rajkot", "mumbai", "delhi"]


//Method-3
var my_array = [5, 4, 7, 8, 9, 2, 7, 5, 4, 8, 7];
unique_array = my_array.filter((item, index, array) => array.indexOf(item) === index);
console.log("Unique Array is : " + unique_array);

//Method - 4
const arr = [
  { id: 1, name: "test1" },
  { id: 2, name: "test2" },
  { id: 2, name: "test3" },
  { id: 3, name: "test4" },
  { id: 4, name: "test5" },
  { id: 5, name: "test6" },
  { id: 5, name: "test7" },
  { id: 6, name: "test8" }
];

const filteredArr = arr.reduce((acc, current) => {
  const x = acc.find(item => item.id === current.id);
  if (!x) {
    return acc.concat([current]);
  } else {
    return acc;
  }
}, []);


//Method - 5
//Here's another possibility using the Map class constructor and values method:
const arr = [
  { id: 1, name: "test1" },
  { id: 2, name: "test2" },
  { id: 2, name: "test3" },
  { id: 3, name: "test4" },
  { id: 4, name: "test5" },
  { id: 5, name: "test6" },
  { id: 5, name: "test7" },
  { id: 6, name: "test8" }
];

const uniqueObjects = [...new Map(arr.map(item => [item.id, item])).values()]


//Method-6

		function removeDuplicates() {
			// Create an array of objects
			books = [
				{ title: "C++", author: "Bjarne" },
				{ title: "Java", author: "James" },
				{ title: "Python", author: "Guido" },
				{ title: "Java", author: "James" },
			];
			// Display the list of array objects
			console.log(books);
			// Declare a new array
			let newArray = [];
			// Declare an empty object
			let uniqueObject = {};
			// Loop for the array elements
			for (let i in books) {
				// Extract the title
				objTitle = books[i]['title'];
				// Use the title as the index
				uniqueObject[objTitle] = books[i];
			}
			// Loop to push unique object into array
			for (i in uniqueObject) {
				newArray.push(uniqueObject[i]);
			}
			// Display the unique objects
			console.log(newArray);
		}


  //Method-7
  function removeDuplicates() {
          // Create an array of objects
          books = [
              { title: "C++", author: "Bjarne" },
              { title: "Java", author: "James" },
              { title: "Python", author: "Guido" },
              { title: "Java", author: "James" },
          ];
          jsonObject = books.map(JSON.stringify);
          console.log(jsonObject);
          uniqueSet = new Set(jsonObject);
          uniqueArray = Array.from(uniqueSet).map(JSON.parse);
          console.log(uniqueArray);
}

//Method- 8
const arr = [
    {place: "here",  name: "x", other: "other stuff1" },
    {place: "there", name: "x", other: "other stuff2" },
    {place: "here",  name: "y", other: "other stuff4" },
    {place: "here",  name: "z", other: "other stuff5" }
]
function getUniqueListBy(arr, key) {
    return [...new Map(arr.map(item => [item[key], item])).values()]
}

//get unique by place
const arr1 = getUniqueListBy(arr, 'place');
//get unique by name
const arr2 = getUniqueListBy(arr, 'name')
Array reducce
//Reference ->  https://sebhastian.com/javascript-sum-array-objects/
//Sometimes, you need to count the sum of property in an array of objects. 
//For example, you may find an array of items, and you want to sum the total quantity a person must pay for the items
let cart = [
  {
    name: "JavaScript book",
    price: 4,
  },
  {
    name: "UGG Women's Hazel Ankle Boot",
    price: 79,
  },
  {
    name: "OXO Good Grips 11-Inch Balloon Whisk",
    price: 9,
  },
];
// totalPrice is 92
let totalPrice = cart.reduce(function (accumulator, item) {
  return accumulator + item.price;
}, 0);


//Perform multiple operations before returning the data
let cart = [
  {
    name: "JavaScript book",
    quantity: 3,
    price: 4,
  },
  {
    name: "UGG Women's Hazel Ankle Boot",
    quantity: 2,
    price: 79,
  },
  {
    name: "OXO Good Grips 11-Inch Balloon Whisk",
    quantity: 5,
    price: 9,
  },
];

// totalPrice is 215

let totalPrice = cart.reduce(function (accumulator, item) {
  return accumulator + item.quantity * item.price;
}, 0);



//Filter the array before reduce
let cart = [
  {
    name: "JavaScript book",
    quantity: 3,
    price: 4,
  },
  {
    name: "UGG Women's Hazel Ankle Boot",
    quantity: 2,
    price: 79,
  },
  {
    name: "OXO Good Grips 11-Inch Balloon Whisk",
    quantity: 5,
    price: 9,
  },
];

// totalPrice is 170

let totalPrice = cart
  .filter(
    (item) =>
      item.name === "JavaScript book" ||
      item.name === "UGG Women's Hazel Ankle Boot"
  )
  .reduce((accumulator, item) => {
    return accumulator + item.quantity * item.price;
  }, 0);
Regex for email validation in Javascript
function email_validator(my_email) {
    var email_pattern = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
    if (email_pattern.test(my_email)) {
        console.log("Email is Valid");
    } else {
        console.log("Email is Invalid");
    }
}

email_validator("[email protected]"); // -> logs - Email is Valid
email_validator("test.com"); // -> logs - Email is Invalid
Compress or minify JSON using Javascript
var json_str = `[
    {
      "type": "people",
      "id": "30",
      "attributes": {
        "name": "John Deo",
        "age": 40,
        "gender": "male"
      }
    }
]`;

var minified_json = JSON.stringify(JSON.parse(json_str));
console.log(minified_json);
Javascript Sort() By Multiple Criteria
const teams = [
    {name: "Aviso1", state: true, priority: 1},
    {name: "aviso3", state: true, priority: 3},
    {name: "Aviso2", state: false, priority: 2},
    {name: "aviso4", state: true, priority: 4},
    {name: "aviso5", state: false, priority: 5},
    {name: "aviso6", state: true, priority: 6}
]
let formated = teams.sort((a, b) => a.state === b.state ?  a.priority - b.priority : b.state - a.state);

console.log(formated)


/*
[
  { name: 'Aviso1', state: true, priority: 1 },
  { name: 'aviso3', state: true, priority: 3 },
  { name: 'aviso4', state: true, priority: 4 },
  { name: 'aviso6', state: true, priority: 6 },
  { name: 'Aviso2', state: false, priority: 2 },
  { name: 'aviso5', state: false, priority: 5 }
]*/
test113142
function hello() {
    return <h1>Hello world</h1>
}
Prettify JSON object or array using JSON.stringify
const json_data = {id: 10001, name: "Tokyo", show: "La Casa De papel"};
const pretty_json_str = JSON.stringify(json_data, undefined, 4);
Convert JSON data to String
const json_obj = { id: 1, name: "John Rick", pin: "000000" };
const json_str = JSON.stringify(json_obj);
Convert String to JSON Data
const str_data = '{"name": "Rick Grimes", "city": "New York","pincode": "000-000"}';

//Parse to json data
const json_data = JSON.parse(str_data);

//Using callback function in JSON.parse
const json_data2 = JSON.parse(str_data, function(key, value) {
    //DO something here
})
wait/delay function
method: {
    async function() {
        //first action
        await this.timeout(3000);//delay
        //second action
    },
    timeout(ms) {
        return new Promise(resolve => {
            window.setTimeout(resolve, ms)
        })
    }
}
Calculate square root of a number using javascript
const num = 100;
const sqrt = Math.sqrt(num);
Check if all array items are equal javascript
const allEqual = arr => arr.every(v => v === arr[0]);
allEqual([1,1,1,1]);  // true
Load or preview html to Iframe using Javascript only
var html = '';
html += '<!DOCTYPE html>\n';
html += '<html lang="en">\n';
html += '<head>\n';
html += '</head>\n';
html += '<body>\n';
html += '<div>Hello World we are here...</div>';
html += '</body>\n';
html += '</html>';

(document.getElementById("iframe_id").contentWindow.document).write(html);
(document.getElementById("iframe_id").contentWindow.document).close();
Get all values as array items from an Object in Javascript
const obj = {
    "id": 20,
    "name": "John Deo",
    "dept": "Computer",
    "pincode": "11111"
};

var obj_values = Object.values(obj);
Get all keys from an object using Javascript
var obj = {
    "name": "Ankit",
    "username": "ankit01",
    "status": "active",
    "contact": "mail"
};

var all_keys = Object.keys(obj);
Convert object {key: value} to Array [[key, value]] Javascript
const obj = { a: 1, b: 2, c: 3 };

const entries = Object.entries(obj);
Check if a string is Palindrome or not using Javascript
function palindrome_checker(str) {
    const converted_str = str.split('').reverse().join('');
    if (str === converted_str) {
        console.log(str + " : String is Palindrome");
    } else {
        console.log(str + " : String is not Palindrome");
    }
}

palindrome_checker('deified');
palindrome_checker('Ankit');
Convert a String to Number or Integer in Javascript
const str = "200";
var num = parseInt(str);
Swapping two values using Destructuring in Javascript
let a = 5;
let b = 8;
[a, b] = [b, a]

console.log([a, b])
Convert a Number or Integer to String in Javascript
const num = 10;
const str = num.toString();
Assign default values to function parameters in Javascript
const func = (arr, arg2 = 0, len = arr.length) => { // Here arg2 and len are parametes with default values.
    return len;
}
const result = func([10, 30, 40, 50, 60]);
console.log(result);
Combine or merge two or multiple arrays into single array in Javascript
const users1 = ['Ankit', 'Gaurav'];
const users2 = ['Abadhesh', 'Sourabh'];
const users3 = ['Arun', 'Avinash'];

//FIRST METHOD - using ...
const all_users1 = [...users1, ...users2, ...users3];

//SECOND METHOD - using .concat()
const all_users2 = users1.concat(users2).concat(users3)
Pass multiple arguments when calling a function which takes single argument Javascript
function func_name(...allArgs) {
    console.log("Paraameter at 3th position : " + arguments[2]);
    console.log("Paraameter at 6th position : " + arguments[5]);
}

func_name("value1", "value2", "value3", "value4", "value5", "value6");
Use of ?? (Nullish Coalescing Operator) in Javascript
const user_name = null ?? 'Ankit';
// Output: "Ankit"

const number = 0 ?? 40;
// Output: 0
Optional Chaining on Javascript Object
const user = {
  admin: {
    name: "John Deo"
  }
};
user.admin?.name;
// "John Deo"
user.admi?.name;
// undefined
user.admi.name
// TypeError: Cannot read property 'name' of undefined
Concatenate multiple objects into one using Javascript
const user = {
    name: 'John Deo',
    gender: 'Male'
};
const role = {
    admin: '1'
};
const details = {
    email: '[email protected]',
    city: 'New York',
};

const final_object = { ...user, ...role, ...details };

console.log(final_object);
How to use Ternary Operator in place of if else statements Javascript
//Simple If else condition using Ternary Operator
const score = 15;
const score_checker = score > 20 ? 'Score is grater than 20' : 'Score is less than 20';
console.log(score_checker);

//Nested If else conditions can be written using Ternary Operator
function check_number(num) {
    return num > 7 ? 'Number is greater than 7'
        : num < 7 ? 'Number is less than 7'
            : num === 7 ? 'Number is equals to 7' : "";
}

console.log(check_number(7));
console.log(check_number(6));
console.log(check_number(10));
Calculate the frequency of characters in a string using Javascript
const str = 'CoNgratulations';

const letters = {};
for (let char of str.toLowerCase()) {
    letters[char] = letters[char] + 1 || 1;
}

console.log(letters);
Remove duplicate values from an array in Javascript
var my_array = [5, 4, 7, 8, 9, 2, 7, 5, 4, 8, 7];

// First Method
unique_array = my_array.filter((item, index, array) => array.indexOf(item) === index);
console.log("Unique Array is : " + unique_array);

// Second Method
var another_uni_arr = [...new Set(my_array)];
console.log("Another Unique Array is : " + another_uni_arr);
Use of logical operators to reduce if else statements Javascript
function run_func(number) {
    // set number to 35 if it is not already set
    number = number || 35;
    console.log("Number is : " + number);
}

const check_this_var = 20;
check_this_var === 20 && run_func();
// SAME AS - if (check_this_var === 20) { run_func(); }
// Output: 10

check_this_var === 5 || run_func();
// SAME AS if (check_this_var != 5) { run_func(); }
// Output: 10
Remove empty, false, undefined values from array Javscript
var my_arr = [4, '', 0, 10, 7, '', false, 10];

my_arr = my_arr.filter(Boolean);

console.log(my_arr);
Get the sum of array values using Javascript - Solved
const myarr = [10, 23, 32, 65, 7, 24];
const sum_of_array = myarr.reduce((a, b) => a + b);
console.log(sum_of_array);
Find the maximum value from an array using Javascript
const myarr = [10, 23, 32, 65, 7, 24];
const max_value = myarr.reduce((a, b) => a > b ? a : b);
console.log(max_value);
Find the minimum value from an array javascript
const myarr = [10, 23, 65, 7, 24];
const min_val = myarr.reduce((a, b) => a < b ? a : b);
console.log(min_val);
Create fixed length array with blank values in it Javascript
var my_arr = Array(7).fill('');

console.log(my_arr);
rascunho
https://dev.to/techygeeky/top-20-javascript-tips-and-tricks-to-increase-your-speed-and-efficiency-283g
Run a Javascript function after user finished writing in the input field
var type_timer;
var finished_writing_interval = 3000;
var my_input = document.getElementById("my_input");

//Start timeout when user start typing
my_input.addEventListener('keyup', function () {
  clearTimeout(type_timer);
  type_timer = setTimeout(finished_typing, finished_writing_interval);
});

//Clear timeout on key down event
my_input.addEventListener('keydown', function () {
  clearTimeout(type_timer);
});

//This function runs when user has finished writing in input
function finished_typing () {
    console.log("User finished typing");
    //Do something here ...
}
Scroll to the bottom of a div using Javascript
var my_div = document.getElementById("my_div");
my_div.scrollTop = my_div.scrollHeight;
Run a function every 5 seconds interval using Javascript
var inverval_timer;

//Time in milliseconds [1 second = 1000 milliseconds ]    
inverval_timer = setInterval(function() { 
    console.log("5 seconds completed");
}, 5000);
    
//IF you want to stop above timer
function stop_timer() {
    clearInterval(inverval_timer); 
}
Remove new line separator from start and end positions of string in Javascript
my_str = "\n\n Hello World \n\n\n";
my_str = my_str.replace(/^\s+|\s+$/g, '');
console.log(my_str);
Order and find elements
carlist.map(element => 
console.log(element.brand +" = "+ element['models'].length )); 

console.log("result ==" + JSON.stringify(carlist.filter(element => element['brand'] ==  'Renault'),null,4)); 



var formatedlsit = []; 
var asceding = []; 
var desceding = []; 


formatedlsit = carlist.map(item => ({
        brand: item.brand,
        totalOfmodels: item.models.length
}));


console.log('--------------------------------------------------')

//console.log('formatedlist');
//console.log(JSON.stringify(formatedlsit, null, 4 ));

/*  asceding = formatedlsit.sort(function(a, b){return a.totalOfmodels - b.totalOfmodels});
desceding =  formatedlsit.sort(function(a, b){return b.totalOfmodels - a.totalOfmodels}); 
console.log('------------------ crescente--------------------------------')
console.log(JSON.stringify(asceding, null, 4 ));
console.log('-------------------decrescente-------------------------------')
console.log(JSON.stringify(desceding, null, 4 ));
console.log("mais modelos " + asceding[0].brand);
console.log("menos modelos" + desceding[0].brand);  */ 

 console.log(formatedlsit.sort(function(a, b){return a.totalOfmodels - b.totalOfmodels}));
console.log(formatedlsit.sort(function(a, b){return b.totalOfmodels - a.totalOfmodels}));
jquery linq
https://www.buildinsider.net/web/jqueryref/059
https://qiita.com/nishiurahiroki/items/5fe52bbcbb91d3181bbd#%E5%80%A4%E3%81%AE%E3%82%BB%E3%83%83%E3%83%88value
https://www.it-swarm-ja.tech/ja/jquery/1%E7%A7%92%E3%81%94%E3%81%A8%E3%81%ABajax%E3%83%AA%E3%82%AF%E3%82%A8%E3%82%B9%E3%83%88%E3%82%92%E5%AE%9F%E8%A1%8C%E3%81%99%E3%82%8B/1042450943/
Check if a variable is null, empty, undefined or false Javascript
if (variable_name) {
    //variable_name will not be null, empty, undefined or false
}
Editorjs blocks - JSON to HTML javascript
function jsonToHtml(jsonStr) {
    obj = JSON.parse(jsonStr);

    html = '';
    obj["blocks"].forEach(function(block, index) {
        switch (block['type']) {
            case 'paragraph':
                html += '<p>'+ block['data']['text'] +'</p>';
                break;
            
            case 'header':
                html += '<h'+ block['data']['level'] +'>'+ block['data']['text'] +'</h'+ block['data']['level'] +'>';
                break;

            case 'raw':
                html += block['data']['html'];
                break;

            case 'list':
                lsType = (block['data']['style'] == 'ordered') ? 'ol' : 'ul';
                html += '<' + lsType + '>';
                block['data']['items'].forEach(function(item, index) {
                    html += '<li>' + item + '</li>';
                });
                html += '</' + lsType + '>';
                break;
            
            case 'code':
                html += '<pre><code class="language-'+ block['data']['lang'] +'">'+ block['data']['code'] +'</code></pre>';
                break;
            
            case 'image':
                html += '<div class="img_pnl"><img src="'+ block['data']['file']['url'] +'" /></div>';
                break;
            
            default:
                break;
        }
    });
    
    return html;
}
Util Array Examples
const allLanguages = [ 'ES', 'EN', 'DE' ]
const usedLanguages = [ { id: 1, lang: 'EN' } ].map(e => e.lang);

var result = allLanguages.filter(e => !usedLanguages.includes(e));
console.log(result)


=================



 const myArrayFiltered = this.AllGroupActive.filter(array => this.workFrontAnomalyType.developmentStageGroupId.some(filter => filter === array.id ));
 const checkAllActive = myArrayFiltered.every(item => item.active);



 ===========================================================
var arr1 = ['a', 'b'];
var arr2 = ['a', 'b', 'c', 'd'];

  let intersection = arr1.filter(x => arr2.includes(x));
  let difference = arr1.filter(x => !arr2.includes(x));

   symmetric difference,

   let difference = arr1
                 .filter(x => !arr2.includes(x))
                 .concat(arr2.filter(x => !arr1.includes(x))); 
=======================

someValues.forEach((element, index) => {
    console.log(`Current index: ${index}`);
    console.log(element);
});

============

 removeAnomaly(anomaly: WorkFrontAnomaly){
        var index = this.workFrontAnomalies.indexOf(anomaly);

        if(index != -1){
            this.workFrontAnomalies.splice(index, 1);
        }
    }
Javascript Map and Filter together
data
    .filter(item => item.workFrontAnomalyTypeId === this.WorkFrontAnomalyTypeId)
    .map(anomaly => ({
        name: anomaly.name,
        id: anomaly.id,
        active: anomaly.active,
        workFrontAnomalyTypeId: anomaly.workFrontAnomalyTypeId,
        impedative: anomaly.impedative
    }));
For loop in Javascript
for (var i = 0; i < 5; i++) {
    console.log(i);
}
Get and set storage in chrome extension
chrome.storage.sync.set({name: value}, function() {
    console.log('value is : ' + value);
});

chrome.storage.sync.get(['name'], function(result) {
    console.log('name is : ' + result.name);
});
open link in new tab using javascript
window.open('https://devsheet.com', '_blank');
Remove item from array in Javascript
const myArray = [2, 5, 9];

const removeIndex = 2;

myArray.splice(removeIndex, 1);

console.log(myArray);
How to Check if Arrays in a Object Are All Empty
var allEmpty = Object.keys(obj).every(function(key){
return obj[key].length === 0
})

//filter 
function isUnPopulatedObject(obj) { 
    return Object.keys( obj ).filter( function(key){
      return obj[ key ].length > 0;  //if any array has a property then filter will return this key.
    }).length == 0; //used == here since you want to check if all are empty
}

//every 
function isUnPopulatedObject(obj) { 
    return Object.keys( obj ).every( function(key){
      return obj[ key ].length == 0;  
    }); 
}

//some 
function isUnPopulatedObject(obj) { 
    return Object.keys( obj ).some( function(key){
      return obj[ key ].length > 0;  
    }) === false; 
}

//es8 
const objectIsEmpty = obj => Object.values(obj).every(
    val => Array.isArray(val) && val.length === 0
);

//every 2 sample 
function objectIsEmpty(obj) {
    return Object.keys(obj).every(key => 
      Array.isArray(obj[key]) && obj[key].length
    );
}
CODE GENERATOR
function makeid(length) {
   var result           = '';
   var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
   var charactersLength = characters.length;
   for ( var i = 0; i < length; i++ ) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
   }
   return result;
}

console.log(makeid(5));
Truthy and Falsy in JavaScript
/*In JavaScript, truthy are expressions which evaluates to boolean true value and falsy evaluates to boolean false value. Unlike other languages, true and false values are not limited to boolean data types and comparisons. It can have many other forms. */


//Falsy Values
false
0 Both positive and negative
0n BigInt, when used as a boolean, follows the same rule as a Number
''
null
undefined
NaN
let a = false
    let b = 0
    let c = -0
    let d = 0n
    let e = ''
    let f = null
    let g = undefined
    let h = NaN
    console.log(Boolean (a))
    console.log(Boolean (b))
    console.log(Boolean (c))
    console.log(Boolean (d))
    console.log(Boolean (e))
    console.log(Boolean (f))
    console.log(Boolean (g))
    console.log(Boolean (h))

//Truthy Values
true
{} An object (whether empty or not)
[] An array (whether empty or not)
25 Numbers (whether positive or negative)
'true' Non empty strings
'false' Non empty strings
new Date() Date object
12n BigInt, when used as a boolean, follows the same rule as a Number
Infinity
JavaScript ES6 filtering object with multiple params
let equipmentsReturn = [
                { id: 23, typeId : 214 , groupId :10, tag:"CM0091"}, 
                { id: 11, typeId : 314 , groupId :10, tag:"CM009"}, 
                { id: 435, typeId : 412 , groupId :10, tag:"CM009"},
                { id: 23231, typeId : 2142312 , groupId :10, tag:"CM009"}, 
                { id: 1231231, typeId : 31444 , groupId :10, tag:"CM009"}, 
                { id: 48882, typeId : 412331 , groupId :10, tag:"CM009"},
                { id: 20, typeId : 12356734 , groupId :10, tag:"CM009"},
                { id: 31, typeId : 8888888 , groupId :10, tag:"CM009"},
                { id: 31236566, typeId : 100 , groupId :10, tag:"CM009"},
                { id: 31236566, typeId : 200 , groupId :10, tag:"CM009"}

            ];
            let arraytype = [214];
            let arraygroupId = [ 86, 77];
            let arraytag = ["CM119","CM977"];

            const filtered = equipmentsReturn.filter(({ typeId ,groupId , tag}) =>
            arraytype.includes(typeId) || arraygroupId.includes(groupId) || arraytag.includes(tag) );
            
           console.log(filtered);
Javascript Async/Await ES7
async function foo() {
    const myPromise = new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("Parwinder"); // resolves with "Parwinder" after 2 seconds
        }, 2000);
    });

    // will not move to the next line until myPromise resolves/rejects
    const name = await myPromise;
    // the execution pauses (or awaits) for the promise

    console.log(name); // Parwinder
}

foo();
Get total sum of specif attribute inside of array of objects
let products = [{
  "id": 1,
  "product_name": "Forester",
  "price": 10
}, {
  "id": 2,
  "product_name": "Rainier",
  "price": 10
}, {
  "id": 3,
  "product_name": "Yukon Denali",
  "price": 10
}, {
  "id": 4,
  "product_name": "Regal",
  "price": 10
}, {
  "id": 5,
  "product_name": "Alcyone SVX",
  "price": 5
}];

let totalPrice = products.reduce((accumulator, current) => {
          return accumulator + current.price;
        }, 0);

//totalPrice 45
Find the shortest string in array
let arr = ["aaaa", "aa", "aa", "aaaaa", "a", "aaaaaaaa"];

console.log(
  arr.reduce(function(a, b) {
    return a.length <= b.length ? a : b;
  })
)
// result a
Finding the max/min value of an attribute in an array of objects
//Mapping formated counting 
var arr = ['one', 'two', 'three']
arr.map(element => ({ valor : element.length, descricao: element}) );

//result of the code above and look like this array...
let array =[
    {
        "valor": 3,
        "descricao": "one"
    },
    {
        "valor": 3,
        "descricao": "twsso"
    },
    {
        "valor": 5,
        "descricao": "threexx"
    }
];

let maxvalue = Math.max.apply(Math,array.map(function(o){return o.valor;}))
let minvalue = Math.min.apply(Math,array.map(function(o){return o.valor;}))

let objmax = array.find(function(o){ return o.valor == maxvalue; })
let objmin = array.find(function(o){ return o.valor == minvalue; })

console.log("max word value" + JSON.stringify(objmax)); 
console.log("min word value" + JSON.stringify(objmin));
Get a bigger word from a javascript array
console.log(longestStringReduce(['boop', 'bloomburg', 'hello']));

function longestStringReduce(arr) {
  return arr.reduce((a, b) => a.length < b.length ? b : a, "");
}

//bigger word
//bloomburg
Get Top MAX and MIN itens inside array Javascript
var maxPoints = [];
var scoreByPattern = [93,17,56,91,98,33,9,38,55,78,29,81,60];

function cloneArray(array) {
    return array.map(function(i){ return i; });
}    
function max3(array) {
    return cloneArray(array).sort(function(a,b) { return b-a; }).slice(0,3);
}
function min3(array) {
     return cloneArray(array).sort(function(a,b) { return a-b; }).slice(0,3);
}

var array=scoreByPattern;
alert("Max:"+ max3(array)[0] +' '+max3(array)[1] +' '+max3(array)[2]);
alert("Min:"+ min3(array)[0] +' '+min3(array)[1] +' '+min3(array)[2]);
// Max:98 93 91
// Min:9 17 29

//Top 5 itens
scoreByPattern.sort((a, b) => b - a).slice(0, 5);
// [98, 93, 91, 81, 78]
Javascript ES6 Template strings
const name = 'Matheus'
const message = `Hello `

console.log(message) // prints "Hello Matheus"
Javascript ES6 Destructuring
const Person = {
  name: "John Snow",
  age: 29,
  sex: "male",
  materialStatus: "single",
  address: {
    country: "Westeros",
    state: "The Crownlands",
    city: "Kings Landing",
    pinCode: "500014",
  },
};

const { address : { state, pinCode }, name } = Person;

console.log(name, state, pinCode) // John Snow The Crownlands 500014
console.log(city) // ReferenceErro

//Extract especif information from objects array
let array = [ {"name":"Joe", "age":17, "sex":"M"},{"name":"Bob", "age":17, "sex":"M"},{"name":"Carl", "age": 35, "sex":"M"}];
let especifArrayAtributes = array.map(x => ({firstname: x.name, age : x.age}));
console.log(especifArrayAtributes); //"[{"firstname":"Joe","age":17},{"firstname":"Bob","age":17},{"firstname":"Carl","age":35}]"
Javascript ES6 Rest Parameters
function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
Javascript ES6 Spread Operator
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1.push(...arr2);
console.log(arr1);
Javascript ES6 Array Filter
const allUsers = [{
        "name": "Zediane Araújo",
        "age": 66,
        "picture": "https://randomuser.me/api/portraits/thumb/women/13.jpg",
        "gender": "female"
    },
    {
        "name": "Nara Porto",
        "age": 70,
        "picture": "https://randomuser.me/api/portraits/thumb/women/77.jpg",
        "gender": "female"
    },
    {
        "name": "Ferafina da Cruz",
        "age": 66,
        "picture": "https://randomuser.me/api/portraits/thumb/women/3.jpg",
        "gender": "female"
    },
    {
        "name": "Cliseu Castro",
        "age": 48,
        "picture": "https://randomuser.me/api/portraits/thumb/men/24.jpg",
        "gender": "male"
    },
    {
        "name": "Aiara Cavalcanti",
        "age": 69,
        "picture": "https://randomuser.me/api/portraits/thumb/women/3.jpg",
        "gender": "female"
    }
];

const filteredUsers = allUsers.filter((user) => {
    const inputValue = "CLI"; //Obtenha valor do input com .value, deixei esse valor para exemplo 
    const valueFilterLower = inputValue.toLowerCase(); //convertendo valor do input para minisculo
    const lowername = user.name.toLowerCase(); // converta o nome atual para minisculo
    return lowername.indexOf(valueFilterLower) > -1; // O método indexOf() retorna o primeiro índice em que o elemento pode ser encontrado no array, retorna -1 caso o mesmo não esteja presente.
    //lembrando que O método filter() cria um novo array com todos os elementos que passaram no teste implementado pela função fornecida.
});

console.log(filteredUsers);
Check if video is stopped or playing Javascript only
var video = document.getElementsByTagName("video");
if (video[0].paused) {
    console.log("video is stopped");
    //DO SOMETING...
} else {
    console.log("video is playing");
    //DO SOMETHING...
}

//OR YOU CAN GET video DOM OBJ USING ID
var video = document.getElementById("videoId");
if (video.paused) {
    console.log("video is stopped");
    //DO SOMETING...
} else {
    console.log("video is playing");
    //DO SOMETHING...
}
Videojs check if video is playing
var videoObj = videojs("video_id");

if (!videoObj.paused()) {
    console.log("Video is playing");
} else {
    console.log("Video is paused");
}

//USING .paused() function of videojs
Get first 10 words from string javascript
function getWordStr(str) {
    return str.split(/\s+/).slice(0, 10).join(" ");
}

//TO CALL THIS FUNCTION
var fullStr = "We can get first 10 words form this string using the above function";
var finalStr = getWordStr(fullStr);

console.log(finalStr);
xhr post request with form data javascript
var data = new FormData();
data.append('username', 'username');
data.append('email', 'email');

var xhr = new XMLHttpRequest();
xhr.open('POST', 'api_url', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
    // YOU WILL FIND RESPONSE HERE
    console.log(this.responseText);
};
xhr.send(data);
Remove last character of a string in Javascript
var str = "Hello World";
var finalStr = str.substring(0, str.length-1);
Testest
dsds
test
test
Generate Unique ID
const uuid = (lenght = 10) =>{
    const charts = "abcdefghijklmnopqrstuvwzywABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    let id = "";
    
    for(let i = 0 ; i < lenght;i++){
        id += charts[Math.floor(Math.random() * charts.length)];
    }
    return id;
}
Password Checker
let passwordChecker = (password) => {
	if (isUpperCase(password) && isLowerCase(password) && isNumber(password) && isProperLength(password) && consOcc(password)){
		return true
	} else {
		return false
	}
}

let consOcc = (password) => {
	let init = password.charAt(0)
	let count = 1
	for (let i=1; i < password.length; i++) {
		if (password.charAt(i) == init) {
			init = password.charAt(i)
			count++
			if (count > 2) {
				return false
			}
		} else {
			init = password.charAt(i)
			count = 1 
		}
	}
	if (count>=3) {
		return false	
	}
	else {
		return true
	}
	// 
}

let isUpperCase = (password) => {
	return /[A-Z]/.test(password)
}

let isLowerCase = (password) => {
	return /[a-z]/.test(password)
}

let isNumber = (password) => {
	return /[0-9]/.test(password)
}

let isProperLength = (password) => {
	if (password.length >= 6 && password.length <= 16) {
		return true;
	}
	return false
}
Promise Chaining
new Promise(function (resolve, reject) {
    setTimeout(() => resolve(1), 1000); // (*)
}).then(function (result) { // (**)
    alert(result); // 1
    return result * 2;
}).then(function (result) { // (***)
    alert(result); // 2
    return result * 2;
}).then(function (result) {
    alert(result); // 4
    return result * 2;
});
Get all child elements of parent element in javascript
var parent = document.getElementById("parent_id");
var childrens = parent.children;
//RETURNS ALL CHILD ELEMENTS HTMLCollection ARRAY
Add new item at first position of array using unshift() method Javascript
var items = ["Apple", "Banana", "Orange"];
items.unshift("Papaya", "Watermelon");
console.log(items);
MAthPix equation
function checkIfEquationExists(str){
    str2 = str.replace(/\["|]/g," ")
    str3 = str2.replace(/[,[]/g," ")
    str4 = str3.replace(/"/g ," ")
    return str4;
}
Loop through object javascript
var items = {
    "item_1": "1",
    "item_2": "2",
    "item_3": "3"
}
for (var item in items) {
    console.log(items[item]);
}
Javascript getAbsolutePath
//Javascript get current url 
function getAbsolutePath() {
    var loc = window.location;
    var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
    return loc.href.substring(0, loc.href.length - ((loc.pathname + loc.search + loc.hash).length - pathName.length));
}
Aerofiler Snippets Javascript
// Aerofiler Search Results Selector 1st column
.ag-header-viewport  .ag-header-container  .ag-header-row:nth-child(1)  .ag-header-cell:nth-child(1)  span.ag-header-cell-text
// Aerofiler Dashboard page - doc activity area- click 1st doc link
document.querySelector("#actTable tbody tr:nth-child(1) a").click()
// Locate and  button using attribute value
document.querySelector("button[data-target='#relatedDocsModal']").click()
document.querySelector("button[data-target='#relatedDocsModal'][data-toggle='modal']").click()
//Search page - get number of doc titles in search results
document.querySelectorAll("div[col-id=title] .wrap").length

//////////////////
//for(count=1;count<=5;count++)
{
  // console.log(document.querySelectorAll("div[role='gridcell'][col-id='startDate']")[count].textContent);
//document.querySelectorAll("div[role='gridcell'][col-id='startDate']")[count].textContent;
}
 // document.querySelectorAll("div[col-id=title] .wrap")[count].innerText;
   //document.querySelectorAll("div[col-id='title'] .wrap")[count].textContent;
//document.querySelectorAll("div[role='gridcell'][col-id='startDate']").textContent

var titles=document.querySelectorAll("div[role='gridcell'][col-id='startDate']");

console.log(titles[1].textContent);
npm module creation/publish
// --  npm module creation
let npmjsAuthCredentials = {
    username : 'purplecrow',
    password : '7600Akshat397973'
}

// -- login using cli

// npm folder  with same name as 
// that in the package & .js file in the package

// npm add user - if needed there for authenticating the 
// user to publish the credentials

// npm version if u want to add new one 
// npm publish
// Note:- Errors - before publishing git tree should be clean
// as without it , the files would not publish.

// -------   -----  for updating the version in the package to be used
//  npm install purplecrow@latest --save


let links = [
'https://stackoverflow.com/questions/15056377/how-do-i-update-an-npm-module-that-i-published#targetText=4%20Answers&targetText=Change%20the%20version%20in%20your,version%20in%20the%20NPM%20repository'
];
Add service worker to your website
//CREATE SERVICE WORKER FILE ON ROOT NAMED AS service-worker.js(Name does not matter)
var cacheName = 'my-web-cache';
var filestoCache = [
    '/css/style.css',
    '/css/main.css',
    '/js/main.js',
    '/images/logo.png'
];

self.addEventListener('install', function(event) {
    event.waitUntil(
      caches.open(cacheName)
        .then(function(cache) {
          console.log('Opened cache');
          return cache.addAll(filestoCache);
        })
    );
});


//CALL SERVICE WORKER FILE AND INSTALL IT(GENERALLY FORM inde.html or other pages)
if ('serviceWorker' in navigator) {
    window.addEventListener('load', function() {
        navigator.serviceWorker.register('/service-worker.js').then(function(registration) {
            console.log('ServiceWorker registration successful with scope: ', registration.scope);
        }, function(err) {
            console.log('ServiceWorker registration failed: ', err);
        });
    });
}
Query selectors in Javascript
//TO SELECT THE VERY FIRST ELEMENT
var element = document.querySelector(".element_class");
//YOU CAN ALSO PASS CHILD HIERARCHY INTO IT
var child_element = document.querySelector(".element_class .child_class");

//TO SELECT ALL ELEMENTS BY CLASS YOU CAN USE BELOW QUERY SELECTOR
var all_elements = document.querySelectorAll(".element_class");

//YOU CAN SLECT ELLEMENTS BY ITS CLASS NAMEs, OR IDs, or BY USING ELEMENTS NAMES LIKE
var all_divs_opn_webpage = document.querySelectorAll("div");
document.addEventListener javascript
document.addEventListener("click", function(){
    console.log("I am clicked")
});

//OR ADD EVENT ON A PARTICULAR EVENT
var button = document.getElementById("button");
button.addEventListener("click", function() {
    console.log("I am clicked on a button");
});
Basic server configuration in Nodejs
const http = require('http');
const app = require('./app');
const port = process.env.PORT || 3500;



const server = http.createServer(app);

server.listen(port);
CORS Headers in Nodejs
app.use((req,res,next)=>{
    res.header('Access-Control-Allow-Origin','*');
    res.header(
        'Access-Control-Allow-Header',
        'Origin,X-Resquested-With,Content-Type,Accept,Authorization'
        );
    if(req.method === 'OPTIONS'){
        res.header(
            'Access-Control-Allow-Methods',
            'GET,POST,PUT,PATCH,DELETE'
            );
        return res.status(200).json({});
    }
    next();
});
indexOf and lastIndexOf a string in javascript
var str = "Check where grapes found";
str.indexOf("grapes"); //It will return 12 as the index

var str = "grapes are not grapes until found";
str.lastIndexOf("grapes"); // Return last index of 'grapes' in str var
JavascriptFirst
var str = "Welcome Developer";
console.log(str);
Get Pseudo elements using Javascript
var elem = window.getComputedStyle(document.querySelector('.element'), ':before');
elem.getPropertyValue('color');
Create random string in Javascript
const result = Math.random().toString(36).substring(2, 15);

console.log(result);
Add class to an element in javascript
var element = document.getElementById("element_id");
element.classList.add("className"); // ADD CLASS TO ELEMENT

element.classList.remove("className"); //REMOVE CLASS FROM ELEMENT
Create form data in Javascript
var form = document.getElementsByTagName("form")[0];
var formData = new FormData(form);

formData.get("title"); //TO GET A KEY(KEY NAME WILL BE name attribute defined in your input controls)
formData.set("title", "This is new title"); //TO SET NEW VALUE TO A KEY

formData.delete("about"); //TO DELETE A KEY FROM FORM DATA
Sort array using Array.sort() in javascript
//SORT ARRAY ALPHABETICALLY
var arr = ["Joe", "Victor", "Henna"];
arr.sort();
arr.reverse(); //DESCENDING ORDER

//SORT ARRAY NUMERICALLY
var numeric_arr = [50, 20, 40, 60, 10, 30];
numeric_arr.sort(function(a, b) { return a - b }); //ASCENDING ORDER
numeric_arr.sort(function(a, b) { return b - a }); //DESCENDING ORDER

//Array of Objects
var fruits = [
    { 'name': 'banana', 'color': 'yellow' },
    { 'name': 'apple', 'color': 'red' },
    { 'name': 'orange', 'color': 'orange' }
];
//SORT ARRAY OF OBJECT
fruits.sort(function (a, b) { return a.name.localeCompare(b.name) });
console.log(fruits);
Replace characters globally Javascript
var str = "Color is Green and green is a cold color";
var result = str.replace(/green/gi, "blue");

console.log(result)

// -> Color is blue and blue is a cold color
Random & Unique CSS Gradient-Color Generator
// HTML CODE
// <h1>Welcome to the game!</h1>
//   <input type="text" name="number" id="" onkeyup="generate(this)"
//      placeholder="Enter your favourite number and then press TAB">
// <div id="result">

let generate = (ele) => {
    if (!isNaN(ele.value)) {
        document.getElementById("result").innerHTML = "";
        // alert(ele.value);
        let letters = "0123456789ABCDEF";
        array_1 = [];
        array_2 = [];
        for (i = 0; i < ele.value; i++) {
            let color_1 = '#';
            let color_2 = '#';
            do {
                for (let i = 0; i < 6; i++) {
                    color_1 += letters[(Math.floor(Math.random() * 16))];
                    color_2 += letters[(Math.floor(Math.random() * 16))];
                }
                array_1.push(color_1);
                array_2.push(color_2);
            } while (!array_1.includes(color_1) && array_2.includes(color_2));
            let div = document.createElement("div");
            div.style.width = "200px";
            div.style.height = "200px";
            div.style.backgroundImage = "linear-gradient(to right," + color_1 + "," + color_2 + ")";
            div.style.color = "white";
            div.style.display = "inline-flex";
            div.style.margin = "25px";
            document.getElementById("result").appendChild(div);
        }
        array_1 = [];
        array_2 = [];
    } else {
        alert("Only Number is allowed");
        document.getElementById("result").innerHTML = "";
    }
}
Super awesome snipper
import patientReducer from '../reducers/patientReducer';
 import joinMultipleApiResponse from '../utils/joinMultipleApiResponse';
 
-const initialState = {};
Array.forEach() in javascript
const myarray = ['1', '2', '3'];

myarray.forEach((item, index) => {
    console.log("item is : " + item + ", index is : " + index);
});
Convert all characters to lowercase using toLowerCase() method in javascript
var str = "World Is Beautiful";
console.log(str.toLowerCase());