Javascript - bigktmbig/MyExperienceAlgorithm GitHub Wiki

  • var check = RegExp('Bearer*');if (check.test(token)) {}
  • endDate.toLocaleDateString('ja-JP'); //2018/12/15
  • new Date for timestamp: new Date(+Milliseconds); or new Date(parseInt(Milliseconds,10));
  • new Date([number time]*1).toISOString()
  • add 0 for date, month: var month = '0' + monthTmp.toString().substr(-2);
  • get array unique element from a given array: function getUniqueElements(array) { var counter = {}; for (var i = 0; i < array.length; ++i) { var key = array[i]; counter[key] = 1; } return Object.keys(counter); }

var unique = getUniqueElements(['cat', 'dog', 'cat']);``console.log(unique); ===============================================================trim and replace extra spaces

  • Resolve 1: // NOTE the possible initial and trailing spaces var str = " The dog has a long tail, and it is RED! " str = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");

// str -> "The dog has a long tail, and it is RED !"

  • Resolve 2: // Trims & replaces any wihtespacing to single space between words String.prototype.clearExtraSpace = function(){ var _trimLeft = /^\s+/, _trimRight = /\s+$/, _multiple = /\s+/g;

    return this.replace(_trimLeft, '').replace(_trimRight, '').replace(_multiple, ' '); }; ================================================================get hour, minute from number

function parseTimeFromNumber(pTime) { var hourActual = '00'; var minuteActual = '00'; hourActual = ('0000' + (parseInt(pTime/100)).toString()).substr(-2); minuteActual = ('0000' + (pTime%100).toString()).substr(-2); // return hourActual + ":" + minuteActual; } ========================================================get unique follow object function getUnique(arr, comp) {

const unique = arr .map(e => e[comp])

 // store the keys of the unique objects
.map((e, i, final) => final.indexOf(e) === i && i)

// eliminate the dead keys & store unique objects
.filter(e => arr[e]).map(e => arr[e]);

return unique; }

console.log(getUnique(arr,'id')

  • Get difference value of arr1 with arr2: Array.prototype.difference = function(e) { return this.filter(function(i) { return e.indexOf(i) < 0; }); };

  • clossure: A Closure is a function defined within another scope that has access to all the variables within the outer scope. A Closure allows us a free environment for the outer function to access the inner functions and inner variables without any scope restrictions. ==============================scroll to element function scrollToDiv(data) { $("html, body").delay(300).animate({ scrollTop: $('.bokrm-wrap-item[data-date="' + data + '"]').offset().top }, 1500);

function scrollToDiv(data) { $("html, body").delay(300).animate({ scrollTop: $('.bokrm-wrap-item[data-date="' + data + '"]').position().top }, 1500); =================================2018/12/26: create calendar

function createCalendarBookingRoomMobile(paramYear, paramMonth, paramDate, action, table) { try { //-------------------------------------------------------// // SET TABLE => to create var table = typeof table !== "undefined" ? table : 'tbl-bokrm-top';

    //-------------------------------------------------------//
    // GET DATE NOW => check date current
    var date          = new Date();
    var thisYear      = date.getFullYear();
    var thisMonth     = date.getMonth()+1;
    var thisDate      = date.getDate();
    
    //-------------------------------------------------------//
    // GET DATE TO REFER
    var getDateMobile = getDateBookingRoomMobile(paramYear, paramMonth, paramDate, 'td-bokrm', table);
    
    //-------------------------------------------------------//
    // SET DATE STATUS
    var getYear       = getDateMobile.getYear;
    var getMonth      = getDateMobile.getMonth.toString().length == 1 ? '0'+getDateMobile.getMonth.toString() : getDateMobile.getMonth;
    var getDate       = getDateMobile.getDate;
    
    var element = $('#view-mobile .mb-calendar #bokrm_top_calendar .' + table);
    
    // focus date
    var numberRow        = getDateMobile.dataDate.length;
    
    // remove backgound chosen
    element.find('.' + table + ' tbody tr td').removeClass('date-chosen');

    // render
    element.each(function(k, h) {
        var _this        = $(this);
        _this.find('tbody tr').each(function(i, e) {
            if (i < numberRow) {
                $(e).find('td').each(function(j, td){
                    // set text color for date of other month
                    if(getDateMobile.dataDate[i][j][4]) {
                        $(td).addClass('other-month');
                    }
                    // set disabled for date of other month in the past and less than current date, sunday, saturday
                    if(getDateMobile.dataDate[i][j][5]) {
                        $(td).addClass('disabled-date');
                    }
                    //set date choose for curent date
                    if(getDateMobile.dataDate[i][j][6]) {
                        $(td).addClass('date-choose');
                    }
                    $(td).text(getDateMobile.dataDate[i][j][2]);

                    // add prefix 0 before what the dates less than 10
                    if(getDateMobile.dataDate[i][j][1] < 10) {
                        getDateMobile.dataDate[i][j][1] = '0' + getDateMobile.dataDate[i][j][1];
                    } 
                    if(getDateMobile.dataDate[i][j][2] < 10) {
                        getDateMobile.dataDate[i][j][2] = '0' + getDateMobile.dataDate[i][j][2];
                    }
                    $(td).attr('data-display-date', getDateMobile.dataDate[i][j][0] + '/' + getDateMobile.dataDate[i][j][1] + '/' + getDateMobile.dataDate[i][j][2]);
                });
            }
        });
    });
    setHeightScreenAgain('mb-calendar');
} catch(e) {
    console.log('createCalendarBookingRoomMobile: ' + e);
}

}

function createCalendarHtmlBookingRoom(row, nameClass, table) { try { var html = ''; var calendarHtml = "









"; for (var i = 0; i < row; i++) { html += calendarHtml; }
    $('.'+table+' tbody').append(html);
} catch(e) {
    console.log('createCalendarHtmlBookingRoom: ' + e);
}

}

function getDateBookingRoomMobile(paramYear, paramMonth, paramDate, nameClass, table) { try { var array1Date = []; var totalDate = 0; var numberRow = 0; var startDate = 0; var array2Date = [];

    var date               = new Date();
        date               = new Date(date.setFullYear(paramYear, paramMonth, paramDate));
    var getYear            = date.getFullYear();
    var getMonth           = date.getMonth();
    var getDate            = date.getDate();
    var getTime            = date.getTime();
    
    var firstDayOfMonth    = date.setDate(1);
    var positionFirstDay   = new Date(firstDayOfMonth).getDay();
    
    var lastDayOfMonth     = new Date(getYear, getMonth + 1, 0).getDate();
    var positionLastDay    = new Date(getYear, getMonth + 1, 0).getDay();
    
    var newFirstDayOfMonth = new Date(firstDayOfMonth);
    
    basicStartDate         = newFirstDayOfMonth.setDate(newFirstDayOfMonth.getDate() - newFirstDayOfMonth.getDay());
    
    totalDate              = positionFirstDay + lastDayOfMonth + (6 - positionLastDay);
    numberRow              = totalDate/7;

    // create html
    $('.'+table+' tbody').empty();
    createCalendarHtmlBookingRoom(numberRow, nameClass, table);

    for(var i = 0; i < totalDate; i++) {
        newStartDate = new Date(basicStartDate).setDate(new Date(basicStartDate).getDate() + i);

        var tmpNewStartDate = new Date(newStartDate);

        array1Date.push([   
                            tmpNewStartDate.getFullYear(),
                            tmpNewStartDate.getMonth() + 1,
                            tmpNewStartDate.getDate(),
                            tmpNewStartDate.getDay(),
                            tmpNewStartDate.getMonth() != getMonth ? 1 : 0,
                            (tmpNewStartDate.getTime() < getTime) ? 1 : 0,
                            (getDate == tmpNewStartDate.getDate() && tmpNewStartDate.getMonth() == getMonth) ? 1 : 0,
                        ]);
    }

    for(var j = 0; j < numberRow; j++) {
        array2Date.push(array1Date.slice(j*7, j*7 + 7));
    }

    return {
            dataDate: array2Date,
            getYear: getYear,
            getMonth: getMonth+1,
            getDate: getDate
        };
} catch(e) {
    console.log('getDateBookingRoomMobile: ' + e);
}

}

==========================================2018/12/26 set height for slick slide /**

  • set height for slide

  • @author :

  • @author :

  • @param : {string}

  • @return : null

  • @access : public

  • @see : init */ function setHeightScreenAgain(screen = '') { try { var heightScreen = $(window).outerHeight(); var heightSlide = $('.slick-current .' + screen).outerHeight(true) + 90;

     if (heightScreen < heightSlide) {
         $(document).find('.slick-list.draggable').height(heightSlide - 90);
     } else {
         if (heightScreen > (heightSlide + 30 + 60)) {//30: margin-bottom of #mb-slide, 60: menu bottom
             $(document).find('.slick-list.draggable').height(heightScreen - 90 - 30 - 60);// 90: header, 30: margin-bottom of #mb-slide, 60: menu bottom
         } else {
             $(document).find('.slick-list.draggable').height(heightScreen - 90 + 30);// 90: header, 30: disparity of margin bottom and menu bottom (60 - 30)
         }
         
     }
    

    } catch(e) { alert('setHeightScreenAgain: ' + e); } } ================================================2018/01/03 weekrange function weekRange(start, end, firstDayName, lastDayName) { try { var results = []; var days = {sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6}; var firstDay = days[firstDayName.toLowerCase().substr(0,3)]; var lastDay = days[lastDayName.toLowerCase().substr(0,3)]; // Copy start date var endDate = new Date(end); var fromDay = new Date(start); var toDay = new Date(start); var dayOfStart = fromDay.getDay(); var isStart = (dayOfStart == 0 || dayOfStart == 6) ? false : true; // Shift to next of required days if(isStart) { fromDay.setDate(fromDay.getDate() + (firstDay - fromDay.getDay() - 7) % 7); }else { fromDay.setDate(fromDay.getDate() + (firstDay - fromDay.getDay() + 7) % 7); } toDay.setDate(toDay.getDate() + (lastDay - toDay.getDay() + 7) % 7); // While less than end date, add dates to result array do { var tmpDate = {}; if(isStart) { tmpDate.date_from = start; isStart = false; }else { tmpDate.date_from = fromDay.toLocaleDateString('ja-JP'); } if(toDay >= endDate) { tmpDate.date_to = end; }else { tmpDate.date_to = toDay.toLocaleDateString('ja-JP'); } //Add dates to date list results.push(tmpDate); //increasing date up to a week fromDay.setDate(fromDay.getDate() + 7); toDay.setDate(toDay.getDate() + 7); }while (fromDay <= endDate) return results; } catch (e) { console.log('weekRange: ' + e.message); } } =======================================2019/01/05 replace var arrb = ['12', '13', '14', '15']; var str = "@!@ fsd@!@ sdf@!@df sds"; var res = str; arrb.forEach(function (item) { res = res.replace(/@!@/, item.toString()); console.log(res); }); setTimeout(function() { console.log(res); }, 2000);

====================================2019/01/07 1.handle keyup $(document).on('keyup', '#blog_textarea', function(evt) { var commentContent = $(this).val().trim(); var regexp = /@+[a-zA-Z0-9]+/g; var checkTag = commentContent.match(regexp); if(checkTag) { evt.preventDefault(); console.log(checkTag); } var coordinates = getCaretCoordinates(this, this.selectionEnd); var topPosition = $(this).position().top + coordinates.top + 12; //position top and padding of textarea var leftPosition = $(this).position().left + coordinates.left + 7; //position left and padding of textarea console.log(topPosition); console.log(leftPosition); $('#wrap_tagger').css('top', topPosition + 'px'); $('#wrap_tagger').css('left', leftPosition + 'px'); }); 2.caret coordinates /* jshint browser: true */

(function () {

// We'll copy the properties below into the mirror div. // Note that some browsers, such as Firefox, do not concatenate properties // into their shorthand (e.g. padding-top, padding-bottom etc. -> padding), // so we have to list every single property explicitly. var properties = [ 'direction', // RTL support 'boxSizing', 'width', // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does 'height', 'overflowX', 'overflowY', // copy the scrollbar for IE

'borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth', 'borderStyle',

'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft',

// https://developer.mozilla.org/en-US/docs/Web/CSS/font 'fontStyle', 'fontVariant', 'fontWeight', 'fontStretch', 'fontSize', 'fontSizeAdjust', 'lineHeight', 'fontFamily',

'textAlign', 'textTransform', 'textIndent', 'textDecoration', // might not make a difference, but better be safe

'letterSpacing', 'wordSpacing',

'tabSize', 'MozTabSize'

];

var isBrowser = (typeof window !== 'undefined'); var isFirefox = (isBrowser && window.mozInnerScreenX != null);

function getCaretCoordinates(element, position, options) { if (!isBrowser) { throw new Error('textarea-caret-position#getCaretCoordinates should only be called in a browser'); }

var debug = options && options.debug || false; if (debug) { var el = document.querySelector('#input-textarea-caret-position-mirror-div'); if (el) el.parentNode.removeChild(el); }

// The mirror div will replicate the textarea's style var div = document.createElement('div'); div.id = 'input-textarea-caret-position-mirror-div'; document.body.appendChild(div);

var style = div.style; var computed = window.getComputedStyle ? window.getComputedStyle(element) : element.currentStyle; // currentStyle for IE < 9 var isInput = element.nodeName === 'INPUT';

// Default textarea styles style.whiteSpace = 'pre-wrap'; if (!isInput) style.wordWrap = 'break-word'; // only for textarea-s

// Position off-screen style.position = 'absolute'; // required to return coordinates properly if (!debug) style.visibility = 'hidden'; // not 'display: none' because we want rendering

// Transfer the element's properties to the div properties.forEach(function (prop) { if (isInput && prop === 'lineHeight') { // Special case for s because text is rendered centered and line height may be != height if (computed.boxSizing === "border-box") { var height = parseInt(computed.height); var outerHeight = parseInt(computed.paddingTop) + parseInt(computed.paddingBottom) + parseInt(computed.borderTopWidth) + parseInt(computed.borderBottomWidth); var targetHeight = outerHeight + parseInt(computed.lineHeight); if (height > targetHeight) { style.lineHeight = height - outerHeight + "px"; } else if (height === targetHeight) { style.lineHeight = computed.lineHeight; } else { style.lineHeight = 0; } } else { style.lineHeight = computed.height; } } else { style[prop] = computed[prop]; } });

if (isFirefox) { // Firefox lies about the overflow property for textareas: https://bugzilla.mozilla.org/show_bug.cgi?id=984275 if (element.scrollHeight > parseInt(computed.height)) style.overflowY = 'scroll'; } else { style.overflow = 'hidden'; // for Chrome to not render a scrollbar; IE keeps overflowY = 'scroll' }

div.textContent = element.value.substring(0, position); // The second special handling for input type="text" vs textarea: // spaces need to be replaced with non-breaking spaces - http://stackoverflow.com/a/13402035/1269037 if (isInput) div.textContent = div.textContent.replace(/\s/g, '\u00a0');

var span = document.createElement('span'); // Wrapping must be replicated exactly, including when a long word gets // onto the next line, with whitespace at the end of the line before (#7). // The only reliable way to do that is to copy the entire rest of the // textarea's content into the created at the caret position. // For inputs, just '.' would be enough, but no need to bother. span.textContent = element.value.substring(position) || '.'; // || because a completely empty faux span doesn't render at all div.appendChild(span);

var coordinates = { top: span.offsetTop + parseInt(computed['borderTopWidth']), left: span.offsetLeft + parseInt(computed['borderLeftWidth']), height: parseInt(computed['lineHeight']) };

if (debug) { span.style.backgroundColor = '#aaa'; } else { document.body.removeChild(div); }

return coordinates; }

if (typeof module != 'undefined' && typeof module.exports != 'undefined') { module.exports = getCaretCoordinates; } else if(isBrowser) { window.getCaretCoordinates = getCaretCoordinates; }

}()); ====================================================2019/01/08 backspace element html function backspaceComment(comment_div, evt) { try { // fix backspace bug in FF // https://bugzilla.mozilla.org/show_bug.cgi?id=685445 var selection = window.getSelection(); if (!selection.isCollapsed || !selection.rangeCount) { return; }

    var curRange = selection.getRangeAt(selection.rangeCount - 1);
    if (curRange.commonAncestorContainer.nodeType == 3 && curRange.startOffset > 0) {
        // we are in child selection. The characters of the text node is being deleted
        return;
    }

    var range = document.createRange();
    if (selection.anchorNode != comment_div) {
        // selection is in character mode. expand it to the whole editable field
        range.selectNodeContents(comment_div);
        range.setEndBefore(selection.anchorNode);
    } else if (selection.anchorOffset > 0) {
        range.setEnd(comment_div, selection.anchorOffset);
    } else {
        // reached the beginning of editable field
        return;
    }
    range.setStart(comment_div, range.endOffset - 1);


    var previousNode = range.cloneContents().lastChild;
    if (previousNode && previousNode.contentEditable == 'false') {
        // this is some rich content, e.g. smile. We should help the user to delete it
        range.deleteContents();
        evt.preventDefault();
    }
} catch(e){
    console.log('backspaceComment: ' + e.message);
}

} ===================================================2019/01/08 blink cursor move to the end text in div contenteditable 1.listen event evt.preventDefault(); var fullName = $(this).text(); var userId = $(this).data('tagger-id'); $('#wrap_tagger').addClass('hide'); //remove string tagger var commentText = $('#blog_textarea').html(); commentText = commentText.replace(_strTagger, ''); $('#blog_textarea').html(commentText); //create eleTag to replace string tagger var eleTag = document.createElement("span"); eleTag.setAttribute('class', 'spn-tagger'); eleTag.setAttribute('contenteditable', 'false'); eleTag.setAttribute('data-tag-user-id', userId); eleTag.innerHTML = fullName + ' '; $('#blog_textarea').append(eleTag); $('#blog_textarea').append(' '); // Move blink cursor to the end (after eleTag) placeCaretAfter(eleTag); 2.range function function placeCaretAfter(el) { el.focus(); if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") { var range = document.createRange(); range.setStartAfter(el); range.collapse(true); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } else if (typeof document.body.createTextRange != "undefined") { var textRange = document.body.createTextRange(); textRange.moveToElementText(el); textRange.collapse(false); textRange.select(); } } ======================================================================2019/01/14 concat string with multiline var style = '<style type="text/css">\n'+ '.reg { font-size: 10pt; color:#000000; font-family:monospace } \n' + '.bigRed { font-size: 14pt; color:#ff0000; font-family:monospace } \n' + '</style>' ======================================================================2019/01/16 window.open() is blocked

  1. add async: false, in ajax. ======================================================================2019/01/16 middle click of mouse
  2. event mousedown with event.button (0: left click, 1: middle click) ======================================================================2019/02/02 mon, sun of week Date.prototype.GetFirstDayOfWeek = function() { return (new Date(this.setDate(this.getDate() - this.getDay()))); }

Date.prototype.GetLastDayOfWeek = function() { return (new Date(this.setDate(this.getDate() - this.getDay() +6))); }

var today = new Date();

alert(today.GetFirstDayOfWeek());

alert(today.GetLastDayOfWeek()); ======================================================2019/03/14 obj is empty function isEmpty(obj) { for(var key in obj) { if(obj.hasOwnProperty(key)) return false; } return true; } =======================================================2019/07/01 handle display time hh:mm const BREAK_TIME_LST = [ {key: 1, value: 60}, {key: 2, value: 45}, {key: 3, value: 30}, {key: 4, value: 15}, {key: 99, value: ''}, {key: 5, value: 0} ]; var time1 = $('#start_time').val(); var time2 = $('#end_time').val(); time1 = time1 != '' ? time1.replace(':','') : 0; time2 = time2 != '' ? time2.replace(':','') : 0; var radioValue = $('input[name=radio-group]:checked').val(); radioValue = timeToNumber(radioValue); radioTime = 0; BREAK_TIME_LST.forEach(function (data) { if(radioValue == 99){ radioTime = timeToNumber($('#rest-time').val()); }else if(radioValue == data.key) { radioTime = data.value; } }); time1 = (parseInt(time1/100)*60) + (time1%100); time2 = (parseInt(time2/100)*60) + (time2%100); var tmpTime = time2 - time1; var totalTime = 0; var hourActual = '00'; var minuteActual = '00'; totalTime = parseInt(tmpTime - radioTime); hourActual = ('0000' + (parseInt(totalTime/60)).toString()).substr(-2); minuteActual = ('0000' + (totalTime%60).toString()).substr(-2); $('#actual').val(hourActual + ":" + minuteActual);

=======================================================2020/10/19 IE browser do not declare default value in function function(ab = '') { // wrong }

function(ab) { // right if(ab === undefinded) { ab = ''; } }

⚠️ **GitHub.com Fallback** ⚠️