Best JavaScript code snippet using ng-mocks
st-grid.js
Source:st-grid.js
1/*!2 * Table Grid Library v3.03 *4 * Copyright 2013, zhangshaolong5 * QQ: 3696699026 * email: zhangshaolongjj@163.com7 *8 */9;var Grid = (function(doc, win){10 var trReg = /@([^(]+)\(([^)]*)\)|\{([^}]+)\}|(\[\])/g,11 propReg = /\{([^}]+)\}/,12 dotReg = /\s*,\s*/,13 pageReg = /\{([^}]+)\}/g,14 isIE = win.navigator.userAgent.indexOf('MSIE') >= 0,15 textContent = 'textContent' in doc ? 'textContent' : 'innerText',16 init = function(options){17 return new Grid(options);18 },19 addEvent = function(node, type, fun, useCapture){20 type = type.replace(/^on/, '');21 node.addEventListener ? node.addEventListener(type, fun, useCapture) :22 node.attachEvent ? node.attachEvent('on' + type, fun) : 23 node['on' + type] = fun;24 },25 initSort = function(o, sorts) {26 var orderBy = o.params[o.mapKeys.orderBy],27 order = o.params[o.mapKeys.order];28 each(sorts, function(sortNode){29 var th = sortNode.node,30 sort = sortNode.sort,31 sortType = sortNode.sortType,32 sp = doc.createElement('span');33 if(orderBy === sort){34 sp.className = 'sort-' + order;35 }else{36 sp.className = 'sort-default';37 }38 th.style.cursor = 'pointer';39 sp.innerHTML = ' ';40 th.appendChild(sp);41 th.onclick = function(sort, sortType){42 return function(){43 var order = 'desc',44 p = {},45 that = this;46 each(sorts, function(sortNode){47 var thNode = sortNode.node,48 sp = thNode.lastChild, cls;49 if(that === thNode){50 if(hasClass(sp, 'sort-desc')){51 order = 'asc';52 }53 cls = 'sort-' + order;54 }else{55 cls = 'sort-default';56 }57 removeClass(sp);58 addClass(sp, cls);59 });60 p[o.mapKeys.order] = order;61 p[o.mapKeys.orderBy] = sort;62 p[o.mapKeys.sortType] = sortType;63 o.send(p);64 }65 }(sort, sortType);66 });67 },68 initParams = function(o, options) {69 o.holder = getNode(options.holder);70 o.bodyTemplate = options.bodyTemplate;71 o.headTemplate = options.headTemplate;72 o.dataSource = options.dataSource;73 o.nopage = options.nopage;74 o.query = options.query || {};75 o.pageNode = getNode(options.pageNode);76 o.sendOnPageSize = options.sendOnPageSize;77 o.noDataMessage = options.noDataMessage || '没ææ°æ®';78 o.ellipsis = options.ellipsis || 'auto';79 o.nostripe = options.nostripe;80 o.sorts = [];81 o.pageTemplate = options.pageTemplate82 || 'æ¯é¡µè¡æ° <select class="page-size"><option value="6">6</option><option value="10">10</option></select> å
±{totalCount}æ¡è®°å½ å
±{totalPage}页 <input type="button" value="é¦é¡µ" class="page-bt first-page" title="é¦é¡µ"> <input type="button" value="ä¸ä¸é¡µ" class="page-bt pre-page" title="ä¸ä¸é¡µ"> 第{pageNo}页 <input type="button" value="ä¸ä¸é¡µ" class="page-bt next-page" title="ä¸ä¸é¡µ"> <input type="button" value="æ«é¡µ" class="page-bt last-page" title="æ«é¡µ"> è·³è½¬è³ <input type="text" size="4" maxlength="5" class="some-page"/>';83 o.params = options.params || {};84 options[o.mapKeys.orderBy] && (o.params[o.mapKeys.orderBy] = options[o.mapKeys.orderBy]);85 options[o.mapKeys.order] && (o.params[o.mapKeys.order] = options[o.mapKeys.order]);86 if (!o.nopage) {87 o.params[o.mapKeys.pageNo] = options[o.mapKeys.pageNo] || 1;88 o.params[o.mapKeys.pageSize] = options[o.mapKeys.pageSize] || 15;89 }90 addClass(o.holder, 'grid');91 mappingKeys(o.mapKeys, options.mapKeys);92 bindResize(o);93 },94 bindResize = function(o){95 var timer = null;96 if(o.ellipsis === 'auto'){97 addEvent(win, 'resize', function(){98 clearTimeout(timer);99 timer = setTimeout(function(){ellipsisColumn(o);}, 200);100 });101 }102 },103 ellipsisColumn = function(o){104 each(o.thead.getElementsByTagName('th'), function(th){105 if(th.scrollWidth > th.clientWidth){106 addClass(th, 'ellipsis');107 th.title = th[textContent];108 o.onellipsised(th);109 }else{110 th.removeAttribute('title');111 }112 });113 each(o.tbody.childNodes, function(tr){114 each(tr.childNodes, function(td){115 if(td.scrollWidth > td.clientWidth){116 addClass(td, 'ellipsis');117 td.title = td[textContent];118 o.onellipsised(td);119 }else{120 td.removeAttribute('title');121 }122 });123 });124 },125 initTable = function(o, options){126 var thead = o.thead = o.holder.tHead,127 tbodies = o.holder.tBodies,128 sorts;129 if(!thead){130 thead = o.thead = createNode('thead');131 o.holder.appendChild(thead);132 }133 if(!tbodies){134 o.holder.appendChild(o.tbody = createNode('tbody'));135 }else{136 o.tbody = tbodies[0];137 }138 if(o.headData || o.headTemplate){139 buildHead(o, o.headData);140 }else{141 sorts = [];142 each(thead.getElementsByTagName('th'), function(th){143 var sort = th.getAttribute(o.mapKeys.sort),144 styles = th.getAttribute(o.mapKeys.styles);145 if(sort){146 sorts.push({147 node:th,148 sort:sort,149 sortType:th.getAttribute(o.mapKeys.sortType)150 });151 }152 if(styles){153 th.style.cssText = styles;154 }155 });156 initSort(o, o.sorts = sorts);157 }158 },159 initPage = function(o, data) {160 o.params[o.mapKeys.totalPage] = data[o.mapKeys.totalPage] = parseInt((data[o.mapKeys.totalCount] - 1) / data[o.mapKeys.pageSize] + 1);161 var btns = [,,,,,[]],162 txt = o.pageTemplate.replace(pageReg, function() {163 return o.params[o.mapKeys[arguments[1]]] = data[o.mapKeys[arguments[1]]];164 }),165 pageNode = o.pageNode;166 if (!pageNode) {167 pageNode = o.pageNode = createNode('div');168 o.holder.parentNode.insertBefore(pageNode, o.holder.nextSibling);169 addClass(pageNode, 'page-node');170 }171 pageNode.innerHTML = txt;172 addClass(pageNode, 'page-node');173 each(pageNode.childNodes, function(btn){174 if(hasClass(btn, 'first-page')){175 btns[0] = btn;176 }else if(hasClass(btn, 'pre-page')){177 btns[1] = btn;178 }else if(hasClass(btn, 'next-page')){179 btns[2] = btn;180 }else if(hasClass(btn, 'last-page')){181 btns[3] = btn;182 }else if(hasClass(btn, 'some-page')){183 btns[4] = btn;184 }else if(hasClass(btn, 'page-size')){185 btns[5].push(btn);186 }187 });188 setPageDisabled(o, btns);189 addPageEvent(o, btns);190 },191 trim = function(txt) {192 return txt = txt + '', txt.trim ? txt.trim() : txt.replace(/^\s+|\s+$/, '');193 },194 getNode = function(ele) {195 return ele && (typeof ele == 'string' ? doc.getElementById(ele)196 : ele.nodeName ? ele : ele[0]);197 },198 mappingKeys = function(keys, keysMap) {199 if (typeof keysMap == 'object') {200 each(keysMap, function(v, p){201 keys[p] = v;202 })203 }204 },205 setTableHTML = function(node, html) {206 var nodeName = node.nodeName,207 firstChild,208 temp,209 htmlParentNode;210 if (isIE && nodeName !== 'TD' && nodeName !== 'TH') {211 temp = node.ownerDocument.createElement('div');212 if(nodeName === 'TR'){213 temp.innerHTML = '<table><tbody><tr>' + html + '</tr></tbody></table>';214 htmlParentNode = temp.firstChild.firstChild.firstChild;215 }else if(nodeName === 'TBODY'){216 temp.innerHTML = '<table><tbody>' + html + '</tbody></table>';217 htmlParentNode = temp.firstChild.firstChild;218 }else if(nodeName === 'THEAD'){219 temp.innerHTML = '<table><thead>' + html + '</thead></table>';220 htmlParentNode = temp.firstChild.firstChild;221 }else if(nodeName === 'TABLE'){222 temp.innerHTML = '<table>' + html + '</table>';223 htmlParentNode = temp.firstChild;224 }225 temp = null;226 each(node.childNodes, function(child){227 node.removeChild(child);228 child = null;229 }, !0);230 while(firstChild = htmlParentNode.firstChild){231 node.appendChild(firstChild);232 }233 } else {234 node.innerHTML = html;235 }236 return node;237 },238 each = function(arr, fun, reverse) {239 var len,240 idx;241 if(!arr) return ;242 len = arr.length;243 if(len){244 if(!reverse){245 for(idx=0; idx<len;) if(fun.call(arr[idx], arr[idx], idx++) === !1){246 break;247 }248 }else{249 for(idx=len; idx>0;) if(fun.call(arr[--idx], arr[idx], idx) === !1){250 break;251 }252 }253 }else if(arr.constructor === Object){254 for(idx in arr) if(fun.call(arr[idx], arr[idx], idx) === !1) {255 break;256 }257 }258 },259 createNode = function(tag, cls){260 var node = doc.createElement(tag);261 cls && (node.className = cls);262 return node;263 },264 buildHead = function(o, headData){265 var thead = o.thead,266 headTemplate = o.headTemplate,267 sorts = o.sorts = [],268 trs = [],269 maxLevel = 0,270 levels = [],271 deepLevelThs = [],272 tr,273 buildRow;274 each(thead.childNodes, function(tr){275 thead.removeChild(tr), tr = null;276 }, !0);277 if(headTemplate){278 tr = parseHeadTemplate(o, headData);279 setTableHTML(thead, tr);280 each(thead.getElementsByTagName('th'), function(th, idx){281 var sort = th.getAttribute(o.mapKeys.sort),282 styles = th.getAttribute(o.mapKeys.styles);283 if(sort){284 sorts.push({285 node:th,286 sort:sort,287 sortType:th.getAttribute(o.mapKeys.sortType)288 })289 th.removeAttribute(o.mapKeys.sort);290 }291 if(styles){292 th.style.cssText = styles;293 }294 o.oncolumned.call(th, th, headData);295 });296 }else{297 buildRow = function(ths, level){298 var tr = trs[level];299 if(!tr){300 if(level > maxLevel){301 maxLevel = level;302 }303 tr = createNode('tr');304 thead.appendChild(tr);305 trs.push(tr);306 }307 each(ths, function(column, idx){308 var th,309 text,310 sort,311 childs,312 styles;313 if(typeof column === 'string'){314 th = createNode('th');315 th.appendChild(doc.createTextNode(column));316 tr.appendChild(th);317 deepLevelThs.push({318 node:th,319 level:level320 });321 }else{322 text = column[o.mapKeys.text];323 sort = column[o.mapKeys.sort];324 childs = column[o.mapKeys.childs];325 styles = column[o.mapKeys.styles];326 th = createNode('th');327 th.appendChild(doc.createTextNode(text));328 tr.appendChild(th);329 if(sort){330 sorts.push({331 node:th,332 sort:column[o.mapKeys.sort],333 sortType:column[o.mapKeys.sortType]334 });335 }336 if(childs){337 th.setAttribute('colSpan', getLastLevelChilds(childs));338 buildRow(childs, level + 1);339 }else{340 deepLevelThs.push({341 node:th,342 level:level343 });344 }345 if(styles){346 th.style.cssText = styles;347 }348 o.oncolumned.call(th, th, ths);349 }350 });351 }352 buildRow(headData, 0);353 each(deepLevelThs, function(nodeInfo){354 var size = maxLevel - nodeInfo.level + 1;355 if(size > 1){356 nodeInfo.node.setAttribute('rowSpan', size);357 nodeInfo.node.style.verticalAlign = 'middle';358 }359 });360 }361 initSort(o, sorts);362 },363 getLastLevelChilds = function(data){364 var count = 0,365 getPathChild = function(data){366 each(data, function(item){367 if(typeof item === 'string'){368 count++;369 }else{370 item.childs ? getPathChild(item.childs) : count++;371 }372 });373 };374 getPathChild(data);375 return count;376 },377 buildBody = function(o, bodyData){378 var trs = '',379 mergeRecord = [],380 lastTrIdx;381 each(bodyData, function(model, index){382 var modelList = flatModel(model, o.mapKeys.childs),383 autoIndex = modelList.length * index;384 each(modelList, function(model, idx){385 o.modifyModel(model);386 trs += parseBodyTemplate(o, model, autoIndex + idx);387 });388 });389 setTableHTML(o.tbody, trs);390 each(trs = o.tbody.getElementsByTagName('tr'), function(tr, trIdx){391 each(tr.childNodes, function(td, tdIdx){392 var merge = td.getAttribute(o.mapKeys.merge),393 edit = td.getAttribute(o.mapKeys.edit),394 tdInfo,395 text,396 preText;397 if(merge === 'true'){398 tdInfo = mergeRecord[tdIdx];399 text = td.innerHTML;400 if(!tdInfo){401 mergeRecord[tdIdx] = tdInfo = {402 preText:text,403 startIdx:trIdx404 };405 }406 preText = tdInfo.preText;407 if(text !== preText){408 mergeTr(trs, mergeRecord, tdInfo.startIdx, trIdx, tdIdx);409 tdInfo.preText = text;410 tdInfo.startIdx = trIdx;411 }412 }413 td.removeAttribute(o.mapKeys.merge);414 if(edit){415 (function(td, edit){416 var value = td.innerHTML;417 td.style.cursor = 'pointer';418 td.ondblclick = function(){419 var input = createNode('input', 'edit-node');420 input.type = 'text';421 input.value = value;422 td.innerHTML = '';423 td.appendChild(input);424 input.focus();425 input.onkeydown = function(e){426 var target;427 e = e || win.event;428 if(e.keyCode === 13){429 target = e.target || e.srcElement;430 e.preventDefault ? e.preventDefault() : e.returnValue = !1;431 if(value !== target.value){432 o.onedited(target, edit, value, value = target.value);433 }434 target.blur();435 }436 };437 input.onblur = function(){438 td.innerHTML = value;439 };440 }441 })(td, edit);442 }443 o.oncolumned.call(td, td, bodyData);444 }, !0);445 o.onrowed.call(tr, tr, bodyData);446 });447 lastTrIdx = trs.length;448 each(mergeRecord, function(tdInfo, tdIdx){449 if(tdInfo){450 mergeTr(trs, mergeRecord, tdInfo.startIdx, lastTrIdx, tdIdx);451 tdInfo = null;452 }453 });454 mergeRecord = null;455 },456 mergeTr = function(trs, mergeRecord, trStart, trEnd, tdIdx){457 var i,458 size,459 td;460 for(i=trStart+1; i<trEnd; i++){461 trs[i].removeChild(trs[i].childNodes[tdIdx]);462 }463 size = trEnd - trStart;464 if(size > 1){465 td = trs[trStart].childNodes[tdIdx];466 td.setAttribute('rowSpan', size);467 td.style.verticalAlign = 'middle';468 }469 },470 emptyBody = function(o, data){471 var colspan = 0;472 var trs = o.thead.getElementsByTagName('tr');473 var trsLen = trs.length;474 each(trs, function(tr, trIdx){475 each(tr.getElementsByTagName('th'), function(th, tdIdx){476 var rowSpan = +th.getAttribute('rowSpan') || 1;477 if(rowSpan === (trsLen - trIdx)){478 colspan += +(th.getAttribute('colSpan')) || 1;479 }480 });481 });482 setTableHTML(o.tbody, '<tr><td style="text-align:center;width:'+ o.thead.clientWidth +'px" colSpan="' + colspan + '">' + o.noDataMessage + '</td></tr>');483 if (!o.nopage) {484 data && (data[o.mapKeys.totalPage] = data[o.mapKeys.pageNo] = 0);485 }486 },487 highlight = function(o) {488 each(o.tbody.childNodes, function(tr, idx){489 if (idx & 1) {490 addClass(tr, 'zebra-even');491 } else {492 removeClass(tr, 'zebra-even');493 }494 tr.onmouseover = function(){495 addClass(this, 'mouseover');496 };497 tr.onmouseout = function(){498 removeClass(this, 'mouseover');499 }500 });501 },502 setPageDisabled = function(o, btns) {503 var firstPage = btns[0],504 prePage = btns[1],505 nextPage = btns[2],506 lastPage = btns[3],507 somePage = btns[4],508 pageNo = o.params[o.mapKeys.pageNo],509 totalPage = o.params[o.mapKeys.totalPage];510 if (pageNo <= 1) {511 if(firstPage){512 firstPage.disabled = !0;513 addClass(firstPage, 'bt-dis');514 }515 if(prePage){516 prePage.disabled = !0;517 addClass(prePage, 'bt-dis');518 }519 }else{520 if(firstPage){521 firstPage.disabled = !1;522 removeClass(firstPage, 'bt-dis');523 }524 if(prePage){525 prePage.disabled = !1;526 removeClass(prePage, 'bt-dis');527 }528 }529 if (pageNo >= totalPage) {530 if(nextPage){531 nextPage.disabled = !0;532 addClass(nextPage, "bt-dis");533 }534 if(lastPage){535 lastPage.disabled = !0;536 addClass(lastPage, "bt-dis");537 }538 }else{539 if(nextPage){540 nextPage.disabled = !1;541 removeClass(nextPage, "bt-dis");542 }543 if(lastPage){544 lastPage.disabled = !1;545 removeClass(lastPage, "bt-dis");546 }547 }548 },549 addPageEvent = function(o, btns) {550 var firstPage = btns[0],551 prePage = btns[1],552 nextPage = btns[2],553 lastPage = btns[3],554 somePage = btns[4],555 pageSizes = btns[5],556 pageNo = o.params[o.mapKeys.pageNo];557 if(firstPage){558 firstPage.onclick = function() {559 goToPage(o, 1);560 };561 }562 if(prePage){563 prePage.onclick = function() {564 goToPage(o, pageNo - 1);565 };566 }567 if(nextPage){568 nextPage.onclick = function() {569 goToPage(o, pageNo + 1);570 };571 }572 if(lastPage){573 lastPage.onclick = function() {574 goToPage(o, o.params[o.mapKeys.totalPage]);575 };576 }577 if(somePage){578 somePage.onkeydown = function(e) {579 e = e || win.event;580 if (e.keyCode == 13) {581 goToPage(o, (e.target || e.srcElement)['value']);582 }583 };584 somePage.style.imeMode = 'disabled';585 somePage.oncontextmenu = function() {586 return !1;587 };588 }589 if(pageSizes.length){590 each(pageSizes, function(pageSize){591 if(pageSize.nodeName === 'SELECT'){592 pageSize.onchange = function(){593 o.params[o.mapKeys.pageSize] = this.value >> 0;594 if(o.sendOnPageSize){595 o.send();596 }597 }598 pageSize.value = o.params[o.mapKeys.pageSize];599 return false;600 }601 pageSize.onclick = function(){602 var that = this;603 each(pageSizes, function(btn){604 if(that === btn){605 addClass(that, 'page-active');606 }else{607 removeClass(btn, 'page-active');608 }609 });610 o.params[o.mapKeys.pageSize] = this.value;611 if(o.sendOnPageSize){612 o.send();613 }614 };615 if(pageSize.value == o.params[o.mapKeys.pageSize]){616 addClass(pageSize, 'page-active');617 }else{618 removeClass(pageSize, 'page-active');619 }620 });621 }622 },623 goToPage = function(o, page){624 var p = {};625 page = ('' + page).replace(/^\s+|\s+$/, '');626 if (!/^\d+$/.test(page))627 return;628 page = +page;629 if (page < 1)630 page = 1;631 if (page > o.params[o.mapKeys.totalPage])632 page = o.params[o.mapKeys.totalPage];633 p[o.mapKeys.pageNo] = page;634 o.send(p);635 },636 flatModel = function(model, deepSign){//ä¸å¤çå±çº§é´keyç¸åçæ
åµï¼ææ¶éè¦ä½¿ç¨è
èªå·±ä¿è¯ã637 var list = [],638 dealModel = function(model, pModel){639 var mol = {};640 each(model, function(value, key){641 if(key !== deepSign){642 mol[key] = value;643 }644 });645 each(pModel, function(pv, pk){646 mol[pk] = pv;647 });648 var childs = model[deepSign];649 if(childs){650 each(childs, function(model){651 dealModel(model, mol);652 });653 }else{654 list.push(mol);655 }656 };657 if(model.constructor === Array){658 each(model, function(model){659 dealModel(model);660 });661 }else{662 dealModel(model);663 }664 return list;665 },666 jsMeta = {667 '\b' : '\\b',668 '\t' : '\\t',669 '\n' : '\\n',670 '\f' : '\\f',671 '\r' : '\\r',672 '\\' : '\\\\'673 },674 htmlMeta = {675 '&' : '&',676 '<' : '<',677 '>' : '>',678 '"' : '"',679 "'" : ''',680 '\\' : '\\\\',681 '\"' : '\\"'682 },683 escapeHTML = function(txt) {684 if (typeof txt == 'undefined')685 return "";686 if (typeof txt != 'string')687 return txt;688 return txt.replace(/\\|\"|&|<|>|"|'/g, function() {689 return htmlMeta[arguments[0]];690 });691 },692 escapeJS = function(str) {693 if (typeof str == 'undefined')694 return ;695 str = str.replace(/[\x00-\x1f\\]/g, function(chr) {696 var special = jsMeta[chr];697 return special ? special : '\\u' + ('0000' + chr.charCodeAt(0).toString(16)).slice(-4);698 });699 return '"' + str.replace(/"/g, '\\"') + '"';700 },701 parseBodyTemplate = function(o, model, idx) {702 return o.bodyTemplate.replace(trReg, function(full, fun, args, prop, autoIdx){703 return parseTemplate(o, fun, args, prop, autoIdx, model, idx);704 });705 },706 parseTemplate = function(o, fun, args, prop, autoIdx, model, idx){707 var size, current, arr;708 if (fun) {709 arr = [];710 each(args.split(dotReg), function(param){711 var isRep = propReg.exec(param), p;712 if (isRep) {713 p = model[isRep[1]];714 if (typeof p == 'string'){715 arr.push(escapeJS(p));716 }else{717 arr.push(p + '');718 }719 } else {720 if (typeof param == 'string'){721 arr.push(escapeJS(param));722 }else{723 arr.push(param + '');724 }725 }726 });727 return eval('0, ' + fun + '(' + arr.join(',') + ')');728 } else if (prop) {729 return model[prop] === undefined ? '' : model[prop];730 } else if(autoIdx){731 if(o.nopage){732 return idx + 1;733 }734 return ((current || (current = o.params[o.mapKeys.pageNo])) - 1) * (size || (size = o.params[o.mapKeys.pageSize])) + idx + 1;735 }736 },737 parseHeadTemplate = function(o, model) {738 return o.headTemplate.replace(trReg, function(full, fun, args, prop, autoIdx){739 return parseTemplate(o, fun, args, prop, autoIdx, model);740 });741 },742 hasClass = function(node, cls){743 var className, find, constructor;744 if(!node) return !1;745 className = ' ' + (node.className ? node.className.replace(/\s+/mg, ' ') : node) + ' ', constructor = cls.constructor;746 if(constructor === String){747 return className.indexOf(' ' + trim(cls) + ' ') > -1;748 }749 if(constructor === RegExp){750 find = !1;751 each(className.split(' '), function(c){752 if(cls.test(c)){753 return !(find = !0);754 }755 });756 return find;757 }758 return !1;759 },760 addClass = function(node, cls){761 var className = node.className,762 used = [];763 cls = trim(cls);764 if(/\s/.test(cls)){765 each(cls.split(/\s+/), function(cls){766 if(!hasClass(className, cls)){767 used.push(cls);768 }769 });770 }else{771 if(!hasClass(className, cls)){772 used.push(cls);773 }774 }775 node.className = trim(className + ' ' + used.join(' '));776 },777 removeClass = function(node, cls){778 if(!cls){779 node.className = '';780 }else{781 var className = ' ' + node.className.replace(/\s+/mg, ' ') + ' ',782 isString = cls.constructor === String, classNames;783 if(isString) cls = trim(cls);784 if(/\s/.test(cls)){785 each(cls.split(/\s+/), function(cls){786 if(hasClass(className, cls)){787 if(isString){788 className = className.replace(' ' + cls + ' ', ' ');789 }else{790 classNames = [];791 each(className.split(/\s+/), function(c){792 if(!cls.test(c)){793 classNames.push(c);794 }795 });796 className = classNames.join(' ');797 }798 }799 });800 }else{801 if(hasClass(className, cls)){802 if(isString){803 className = className.replace(' ' + cls + ' ', ' ');804 }else{805 classNames = [];806 each(className.split(/\s+/), function(c){807 if(!cls.test(c)){808 classNames.push(c);809 }810 });811 className = classNames.join(' ');812 }813 }814 }815 node.className = trim(className.split(/\s+/).join(' '));816 }817 },818 fill = function(o, data){819 var headData, bodyData;820 if (data && typeof data == 'object') {821 headData = data[o.mapKeys.headData];822 bodyData = data[o.mapKeys.bodyData];823 if(data[o.mapKeys.bodyTemplate]){824 o.bodyTemplate = data[o.mapKeys.bodyTemplate];825 }826 if(data[o.mapKeys.headTemplate]){827 o.headTemplate = data[o.mapKeys.headTemplate];828 }829 if(headData || o.headTemplate){830 buildHead(o, o.headData = headData);831 }832 if(bodyData && bodyData.length){833 buildBody(o, o.bodyData = bodyData);834 } else {835 emptyBody(o, data);836 }837 } else {838 emptyBody(o, data);839 }840 if (!o.nopage) {841 initPage(o, data);842 }843 if(!o.nostripe){844 highlight(o);845 }846 if(o.ellipsis === 'auto'){847 ellipsisColumn(o);848 }849 o.onfilled(data);850 };851 var Grid = function(options) {852 this.mapKeys = {853 pageNo : 'pageNo',854 pageSize : 'pageSize',855 query : 'query',856 body : 'body',857 order : 'order',858 orderBy : 'orderBy',859 totalCount : 'totalCount',860 totalPage : 'totalPage',861 headTemplate : 'headTemplate',862 bodyTemplate : 'bodyTemplate',863 sort : 'sort',864 sortType : 'sortType',865 merge : 'merge',866 styles : 'styles',867 edit : 'edit',868 text : 'text',869 childs : 'childs',870 headData : 'headData',871 bodyData : 'bodyData'872 };873 initParams(this, options);874 initTable(this, options);875 };876 Grid.prototype.send = function(params) {877 var that = this, constructor = this.dataSource.constructor;878 this.beforeSend(params);879 if (typeof params == 'object') {880 each(params, function(val, p){881 that.params[that.mapKeys[p] || p] = val;882 })883 }884 if(!this.nopage){885 if(this.params[this.mapKeys.pageNo] < 1){886 this.params[this.mapKeys.pageNo] = 1;887 }888 }889 if(constructor === String){890 $.ajax({891 url : this.dataSource,892 data : this.params && JSON.stringify(this.params),893 contentType : "application/json",894 type : this.method || 'POST',895 dataType : 'json',896 context : this,897 success : function(data){fill(that, data);},898 error : this.onerror899 });900 }else if(constructor === Function){901 fill(this, this.dataSource(this.params));902 }else if(constructor === Object){903 fill(this, this.dataSource);904 }905 };906 Grid.prototype.destroy = function(){907 this.holder.removeChild(this.thead);908 this.holder.removeChild(this.tbody);909 this.holder.parentNode.removeChild(this.holder);910 if(this.pageNode){911 this.pageNode.parentNode.removeChild(this.pageNode);912 }913 this.holder = this.thead = this.tbody = this.pageNode = null;914 };915 each(['beforeSend', 'modifyModel', 'oncolumned', 'onrowed', 'onfilled', 'onedited', 'onerror', 'onellipsised'], function(method){916 Grid.prototype[method] = function(fun){917 if(fun && fun.constructor === Function){918 this[method] = fun;919 }920 return this;921 };922 });923 Grid.init = init;924 Grid.flatModel = flatModel;925 return Grid;
...
connect-4-stats.js
Source:connect-4-stats.js
1const { MessageEmbed } = require('discord.js');2const fs = require('fs');3var shortAuthor;4var w = 0;5var d = 0;6var l = 0;7var tot = 0;8var playerMap = new Map();9var mapKeys = [];10var brainName;11module.exports = {12 commands: ['connect-4-stats', 'connect-4-stat', 'c4-stat', 'c4-stats'],13 minArgs: 0,14 maxArgs: 1,15 callback: (message, arguments) => {16 try {17 if (arguments.length > 0) {18 shortAuthor = "" + arguments[0];19 if (shortAuthor.indexOf('>') > 0)20 shortAuthor = shortAuthor.substr(3, 18);21 } else {22 shortAuthor = message.author.id;23 }24 if (!fs.existsSync('./assets/connect-4/game-record/' + shortAuthor + '.dat') && shortAuthor != '699366687455051808') {25 message.channel.send("Sorry but I couldn't find match hisotry for id: " + shortAuthor)26 return;27 }28 if (shortAuthor == '699366687455051808') {29 for (var braneSize = 10000; braneSize <= 10000000; braneSize *= 10) {30 if (!fs.existsSync('./assets/connect-4/game-record/' + braneSize + '_computerBrain.dat'))31 continue;32 if (braneSize >= 1000000)33 var title = braneSize.toFixed(0).substring(0, braneSize.toFixed(0).length - 6) + 'M'34 else35 var title = braneSize.toFixed(0).substring(0, braneSize.toFixed(0).length - 3) + 'K'36 getAndPrint(braneSize + '_computerBrain', 'Record for bot brain sized ' + title, message)37 }38 getAndPrint("community", 'Community Brain', message)39 return;40 }41 getAndPrint(shortAuthor, 'Connect 4 stats', message)42 } catch (err) {43 message.channel.send("An error has occured loading stats: " + err.message);44 }45 }46}47function getAndPrint(shortAuthor, title = 'Connect 4 stats', message) {48 if (shortAuthor == "community") {49 if (!fs.existsSync('./assets/connect-4/game-record/0_computerBrain.dat')) {50 message.reply("Could not find stats for " + shortAuthor)51 return;52 }53 var playerGames = fs.readFileSync('./assets/connect-4/game-record/0_computerBrain.dat').toString().split('\n');54 } else {55 if (!fs.existsSync('./assets/connect-4/game-record/' + shortAuthor + '.dat')) {56 message.reply("Could not find stats for " + shortAuthor)57 return;58 }59 var playerGames = fs.readFileSync('./assets/connect-4/game-record/' + shortAuthor + '.dat').toString().split('\n');60 }61 w = 0;62 d = 0;63 l = 0;64 tot = 0;65 playerMap = new Map();66 mapKeys = [];67 for (var i = 0; i < playerGames.length - 1; i++) {68 if (!playerMap.has(playerGames[i].substr(2))) {69 playerMap.set(playerGames[i].substr(2), [0, 0, 0, 0]);70 mapKeys.push(playerGames[i].substr(2));71 }72 playerMap.get(playerGames[i].substr(2))[3]++;73 switch (playerGames[i].charAt(0)) {74 case 'W':75 playerMap.get(playerGames[i].substr(2))[0]++;76 w++;77 break;78 case 'D':79 playerMap.get(playerGames[i].substr(2))[1]++;80 d++;81 break;82 case 'L':83 playerMap.get(playerGames[i].substr(2))[2]++;84 l++;85 }86 tot++;87 }88 var out = "Opponent: W/D/L";89 for (var j = playerMap.size; j > 0 && playerMap.size > 0; j--) {90 var rec = 0;91 var recDex = -1;92 for (var i = 0; i < playerMap.size; i++) {93 if (playerMap.get(mapKeys[i])[3] > rec) {94 rec = playerMap.get(mapKeys[i])[3];95 recDex = i;96 }97 }98 if (recDex == -1)99 break;100 if (!mapKeys[recDex].includes('>')) {101 if (parseInt(mapKeys[recDex]) >= 1000000) {102 brainName = mapKeys[recDex].substring(0, mapKeys[recDex].length - 6) + 'M'103 out += "\nBrain size " + brainName + ': ' + playerMap.get(mapKeys[recDex])[0] + '/' + playerMap.get(mapKeys[recDex])[1] + '/' + playerMap.get(mapKeys[recDex])[2];104 } else105 if (parseInt(mapKeys[recDex]) == 0) {106 brainName = "Community Brain";107 out += "\n" + brainName + ': ' + playerMap.get(mapKeys[recDex])[0] + '/' + playerMap.get(mapKeys[recDex])[1] + '/' + playerMap.get(mapKeys[recDex])[2];108 } else {109 brainName = mapKeys[recDex].substring(0, mapKeys[recDex].length - 3) + 'K';110 out += "\nBrain size " + brainName + ': ' + playerMap.get(mapKeys[recDex])[0] + '/' + playerMap.get(mapKeys[recDex])[1] + '/' + playerMap.get(mapKeys[recDex])[2];111 }112 } else113 out += "\n" + mapKeys[recDex] + ': ' + playerMap.get(mapKeys[recDex])[0] + '/' + playerMap.get(mapKeys[recDex])[1] + '/' + playerMap.get(mapKeys[recDex])[2];114 playerMap.delete(mapKeys[recDex]);115 mapKeys.splice(recDex, 1);116 }117 out += "\n-------------------------------";118 if (shortAuthor == "community") {119 if (fs.existsSync('./assets/connect-4/tournaments/game-record/0_computerBrain.dat'))120 var tourneyGames = fs.readFileSync('./assets/connect-4/tournaments/game-record/0_computerBrain.dat').toString().split('\n');121 } else {122 if (fs.existsSync('./assets/connect-4/tournaments/game-record/' + shortAuthor + '.dat'))123 var tourneyGames = fs.readFileSync('./assets/connect-4/tournaments/game-record/' + shortAuthor + '.dat').toString().split('\n');124 }125 if (tourneyGames != undefined) {126 playerMap = new Map();127 mapKeys = []128 for (var i = 0; i < tourneyGames.length - 1; i++) {129 if (!playerMap.has(tourneyGames[i].substr(2))) {130 playerMap.set(tourneyGames[i].substr(2), [0, 0, 0, 0]);131 mapKeys.push(tourneyGames[i].substr(2));132 }133 playerMap.get(tourneyGames[i].substr(2))[3]++;134 switch (tourneyGames[i].charAt(0)) {135 case 'W':136 playerMap.get(tourneyGames[i].substr(2))[0]++;137 w++;138 break;139 case 'D':140 playerMap.get(tourneyGames[i].substr(2))[1]++;141 d++;142 break;143 case 'L':144 playerMap.get(tourneyGames[i].substr(2))[2]++;145 l++;146 }147 tot++;148 }149 out += "\nTournament stats:";150 for (var j = playerMap.size; j > 0 && playerMap.size > 0; j--) {151 var rec = 0;152 var recDex = -1;153 for (var i = 0; i < playerMap.size; i++) {154 if (playerMap.get(mapKeys[i])[3] > rec) {155 rec = playerMap.get(mapKeys[i])[3];156 recDex = i157 }158 }159 if (recDex == -1)160 break;161 if (!mapKeys[recDex].includes('>')) {162 if (parseInt(mapKeys[recDex]) >= 1000000) {163 brainName = mapKeys[recDex].substring(0, mapKeys[recDex].length - 6) + 'M'164 out += "\nBrain size " + brainName + ': ' + playerMap.get(mapKeys[recDex])[0] + '/' + playerMap.get(mapKeys[recDex])[1] + '/' + playerMap.get(mapKeys[recDex])[2];165 } else166 if (parseInt(mapKeys[recDex]) == 0) {167 brainName = "Community Brain"168 out += "\n" + brainName + ': ' + playerMap.get(mapKeys[recDex])[0] + '/' + playerMap.get(mapKeys[recDex])[1] + '/' + playerMap.get(mapKeys[recDex])[2];169 } else {170 brainName = mapKeys[recDex].substring(0, mapKeys[recDex].length - 3) + 'K'171 out += "\nBrain size " + brainName + ': ' + playerMap.get(mapKeys[recDex])[0] + '/' + playerMap.get(mapKeys[recDex])[1] + '/' + playerMap.get(mapKeys[recDex])[2];172 }173 } else174 out += "\n" + mapKeys[recDex] + ': ' + playerMap.get(mapKeys[recDex])[0] + '/' + playerMap.get(mapKeys[recDex])[1] + '/' + playerMap.get(mapKeys[recDex])[2];175 playerMap.delete(mapKeys[recDex]);176 mapKeys.splice(recDex, 1);177 }178 } else {179 out += '\nCould not find tournament stats! Participate in a tournament to get tournament stats!'180 }181 out += "\nLifetime record: " + w + '/' + d + '/' + l;182 out += "\nLifetime wr: " + (100 * w / tot).toFixed(2) + '%';183 out += "\nLifetime games: " + tot;184 const ch = new MessageEmbed()185 .setColor('#0cc0b4')186 .setTitle(title)187 .setDescription(out)188 .setTimestamp();189 message.channel.send(ch);...
respond-for.js
Source:respond-for.js
...42);43const mapsByComponent = {44 AccountLogin: new Map(),45 AccountClaim: new Map(),46 ProjectList: mapKeys(['projects', 'users']),47 ProjectHome: mapKeys(['project']),48 ProjectShow: new Map(),49 ProjectOverview: mapKeys(['forms']),50 ProjectUserList: mapKeys(['roles', 'projectAssignments']),51 FieldKeyList: mapKeys(['fieldKeys']),52 ProjectFormAccess: mapKeys([53 'forms',54 'fieldKeys',55 'roles',56 'formSummaryAssignments'57 ]),58 ProjectSettings: new Map(),59 FormShow: mapKeys(['form', 'formDraft', 'attachments']),60 FormOverview: new Map(),61 FormVersionList: mapKeys(['formVersions']),62 FormSubmissions: mapKeys(['keys', 'fields', 'submissionsChunk']),63 PublicLinkList: mapKeys(['publicLinks']),64 FormSettings: new Map(),65 FormDraftStatus: mapKeys(['formVersions']),66 FormAttachmentList: new Map(),67 FormDraftTesting: mapKeys(['keys', 'fields', 'submissionsChunk']),68 UserHome: new Map(),69 UserList: mapKeys(['users', 'actors']),70 UserEdit: mapKeys(['user']),71 SystemHome: new Map(),72 BackupList: mapKeys(['backupsConfig', 'audits'], {73 audits: () => testData.standardAudits.sorted()74 }),75 AuditList: mapKeys(['audits'])76};77export default (name) => {78 const map = mapsByComponent[name];79 if (map == null) throw new Error(`unknown component ${name}`);80 return map;...
Using AI Code Generation
1import { mapKeys } from 'ng-mocks';2import { mapKeys } from 'ng-mocks';3import { mapKeys } from 'ng-mocks';4import { mapKeys } from 'ng-mocks';5import { mapKeys } from 'ng-mocks';6import { mapKeys } from 'ng-mocks';7import { mapKeys } from 'ng-mocks';8import { mapKeys } from 'ng-mocks';9import { mapKeys } from 'ng-mocks';10import { mapKeys } from 'ng-mocks';11import { mapKeys } from 'ng-mocks';12import { mapKeys } from 'ng-mocks';13import { mapKeys } from 'ng-mocks';14import { mapKeys } from 'ng-mocks';15import { mapKeys } from 'ng-mocks';16import { mapKeys } from 'ng-mocks';17import { mapKeys } from 'ng-mocks';18import { mapKeys } from 'ng-mocks';19import { mapKeys } from 'ng-mocks';20import { mapKeys } from 'ng
Using AI Code Generation
1import { mapKeys } from 'ng-mocks';2const myObject = {3};4const result = mapKeys(myObject, (value, key) => {5 return key + value;6});7import { mapValues } from 'ng-mocks';8const myObject = {9};10const result = mapValues(myObject, (value, key) => {11 return key + value;12});13import { mockComponent } from 'ng-mocks';14const MyComponent = mockComponent({15});16import { mockDirective } from 'ng-mocks';17const MyDirective = mockDirective({18});19import { mockInstance } from 'ng-mocks';20const MyService = mockInstance(MyService, {21 method: () => 'foo',22});23import { mockPipe } from 'ng-mocks';24const MyPipe = mockPipe({25});26import { mockProvider } from 'ng-mocks';27const MyService = mockProvider(MyService, {28 method: () => 'foo',29});30import { mockRender } from 'ng-mocks';31const fixture = mockRender(MyComponent);32import { mockReset }
Using AI Code Generation
1import { mapKeys } from 'ng-mocks';2import { MockBuilder, MockRender } from 'ng-mocks';3describe('TestComponent', () => {4 beforeEach(() => MockBuilder(TestComponent));5 it('should render', () => {6 const fixture = MockRender(TestComponent);7 expect(fixture.point.componentInstance).toBeDefined();8 });9});10describe('TestComponent', () => {11 it('should render', () => {12 const fixture = MockRender(TestComponent);13 mapKeys(fixture.point.componentInstance, {14 });15 expect(fixture.point.componentInstance).toBeDefined();16 });17});18describe('TestComponent', () => {19 beforeEach(() => MockBuilder(TestComponent));20 it('should render', () => {21 const fixture = MockRender(TestComponent);22 expect(fixture.point.componentInstance).toBeDefined();23 });24});25describe('TestComponent', () => {26 it('should render', () => {27 const fixture = MockRender(TestComponent);28 mapKeys(fixture.point.componentInstance, {29 });30 expect(fixture.point.componentInstance).toBeDefined();31 });32});33describe('TestComponent', () => {34 beforeEach(() => MockBuilder(TestComponent));35 it('should render', () => {36 const fixture = MockRender(TestComponent);37 expect(fixture.point.componentInstance).toBeDefined();38 });39});40describe('TestComponent', () => {41 it('should render', () => {42 const fixture = MockRender(TestComponent);43 mapKeys(fixture.point.componentInstance, {44 });45 expect(fixture.point.componentInstance).toBeDefined();46 });47});48describe('TestComponent', () => {49 beforeEach(() => MockBuilder(TestComponent));50 it('should render', () => {51 const fixture = MockRender(TestComponent);52 expect(fixture.point.componentInstance).toBeDefined();53 });54});55describe('TestComponent', () => {56 it('should render', () => {57 const fixture = MockRender(Test
Using AI Code Generation
1import { mapKeys } from 'ng-mocks';2import mapKeys from 'lodash/mapKeys';3import { mapValues } from 'ng-mocks';4import mapValues from 'lodash/mapValues';5import { matches } from 'ng-mocks';6import matches from 'lodash/matches';7import { matchesProperty } from 'ng-mocks';8import matchesProperty from 'lodash/matchesProperty';9import { max } from 'ng-mocks';10import max from 'lodash/max';11import { maxBy } from 'ng-mocks';12import maxBy from 'lodash/maxBy';13import { mean } from 'ng-mocks';14import mean from 'lodash/mean';15import { meanBy } from 'ng-mocks';16import meanBy from 'lodash/meanBy';17import { memoize } from 'ng-mocks';18import memoize from 'lodash/memoize';19import
Using AI Code Generation
1import {mapKeys} from 'ng-mocks';2import {MyModule} from 'my-module';3import {mockModule} from 'ng-mocks';4import {MyModule} from 'my-module';5import {mockComponent} from 'ng-mocks';6import {MyComponent} from 'my-component';7import {mockDirective} from 'ng-mocks';8import {MyDirective} from 'my-directive';9import {mockPipe} from 'ng-mocks';10import {MyPipe} from 'my-pipe';11import {mockService} from 'ng-mocks';12import {MyService} from 'my-service';13import {mockProvider} from 'ng-mocks';14import {MyProvider} from 'my-provider';15import {mockRender} from 'ng-mocks';16import {MyComponent} from 'my-component';17import {mockReset} from 'ng-mocks';18import {MyModule} from 'my-module';19import {mockReset} from 'ng-mocks';20import {MyModule} from 'my-module';21mockModule(22 ...imports: Array<Type<any> | ModuleWithProviders | any[]>23): any;24import {mockModule} from 'ng-mocks';25import {MyModule} from 'my-module';26describe('MyModule', () => {27 beforeEach(() => {28 mockModule(MyModule);29 });30 it('should be created', () => {31 expect(MyModule).toBeDefined();32 });33});34mockComponent(35 ...imports: Array<Type<any> | ModuleWithProviders | any[]>36): any;37import {mockComponent} from 'ng-mocks';38import {MyComponent} from 'my-component';39describe('MyComponent', () => {40 beforeEach(() =>
Using AI Code Generation
1const mock = jest.fn();2mock.mockReturnValue({ a: 1, b: 2 });3const result = mock();4expect(result).toEqual({ a: 1, b: 2 });5expect(mock).toHaveBeenCalled();6const mock = jasmine.createSpy('mock');7mock.and.returnValue({ a: 1, b: 2 });8const result = mock();9expect(result).toEqual({ a: 1, b: 2 });10expect(mock).toHaveBeenCalled();11const mock = sinon.stub().returns({ a: 1, b: 2 });12const result = mock();13expect(result).toEqual({ a: 1, b: 2 });14expect(mock).toHaveBeenCalled();15const mock = sinon.stub().returns({ a: 1, b: 2 });16const result = mock();17expect(result).toEqual({ a: 1, b: 2 });18expect(mock).toHaveBeenCalled();19const mock = jasmine.createSpy('mock').and.returnValue({ a: 1, b: 2 });20const result = mock();21expect(result).toEqual({ a: 1, b: 2 });22expect(mock).toHaveBeenCalled();23const mock = sinon.stub().returns({ a: 1, b: 2 });24const result = mock();25expect(result).toEqual({ a: 1, b: 2 });26expect(mock).toHaveBeenCalled();27const mock = jest.fn().mockReturnValue({ a: 1, b: 2 });28const result = mock();29expect(result).toEqual({ a: 1, b: 2 });30expect(mock).toHaveBeenCalled();31const mock = jasmine.createSpy('mock').and.returnValue({ a: 1, b: 2 });32const result = mock();33expect(result).toEqual({ a: 1, b: 2 });34expect(mock).toHaveBeenCalled();35const mock = sinon.stub().returns({ a: 1, b:
Using AI Code Generation
1import { mapKeys } from 'ng-mocks';2const obj = { foo: 'bar' };3const result = mapKeys(obj, (value, key) => {4 if (key === 'foo') {5 return 'bar';6 }7 return key;8});9console.log(result);10import { mapValues } from 'ng-mocks';11const obj = { foo: 'bar' };12const result = mapValues(obj, (value, key) => {13 if (key === 'foo') {14 return 'bar';15 }16 return value;17});18console.log(result);19import { mockComponent } from 'ng-mocks';20const MockComponent = mockComponent({21});22console.log(MockComponent);23import { mockDirective } from 'ng-mocks';24const MockDirective = mockDirective({25});26console.log(MockDirective);27import { mockPipe } from 'ng-mocks';28const MockPipe = mockPipe({29});30console.log(MockPipe);31import { mockProvider } from 'ng-mocks';32const MockProvider = mockProvider({33});34console.log(MockProvider);35import { mockRender } from 'ng-mocks';36const MockComponent = mockRender('<mock-component></mock-component>');37console.log(Mock
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!