Best JavaScript code snippet using best
masterdetailgrid.js
Source:masterdetailgrid.js  
1var MDInstance = Array();2var ReloadScreenAfterEdit = 0;3GlobalVariable_getVariable('MasterDetail_ReloadScreenAfterEdit', 0).then(function (response) {4	let obj = JSON.parse(response);5	ReloadScreenAfterEdit = obj.MasterDetail_ReloadScreenAfterEdit;6});7var masterdetailwork = {8	moveup: (MDGrid, recordid, module, rowkey) => {9		if (rowkey == 0) {10			return false;11		}12		let prevrowkey = rowkey-1;13		let previd = MDInstance[MDGrid].getValue(prevrowkey, 'record_id') || '';14		let mapname = document.getElementById(MDGrid.substring(6)).dataset.mapname;15		var fileurl = 'module=Utilities&action=UtilitiesAjax&file=MasterDetailGridLayoutActions&mdaction=move&direction=up&recordid='+recordid+'&previd='+previd+'&detail_module='+module+'&mapname='+mapname;16		jQuery.ajax({17			method: 'POST',18			url: 'index.php?' + fileurl19		}).done(function (response) {20			let res = JSON.parse(response);21			if (res.success) {22				MDInstance[MDGrid].readData(1);23			}24		});25	},26	movedown: (MDGrid, recordid, module, rowkey) => {27		let prevrowkey = rowkey+1;28		let previd = MDInstance[MDGrid].getValue(prevrowkey, 'record_id') || '';29		let mapname = document.getElementById(MDGrid.substring(6)).dataset.mapname;30		var fileurl = 'module=Utilities&action=UtilitiesAjax&file=MasterDetailGridLayoutActions&mdaction=move&direction=down&recordid='+recordid+'&previd='+previd+'&detail_module='+module+'&mapname='+mapname;31		jQuery.ajax({32			method: 'POST',33			url: 'index.php?' + fileurl34		}).done(function (response) {35			let res = JSON.parse(response);36			if (res.success) {37				MDInstance[MDGrid].readData(1);38			} else {39				alert(alert_arr.Failed);40			}41		});42	},43	delete: (MDGrid, module, recordid) => {44		if (confirm(alert_arr.ARE_YOU_SURE)) {45			let mapname = document.getElementById(MDGrid.substring(6)).dataset.mapname;46			var fileurl = 'module=Utilities&action=UtilitiesAjax&file=MasterDetailGridLayoutActions&mdaction=delete&detail_module='+module+'&detail_id='+recordid+'&mapname='+mapname;47			jQuery.ajax({48				method: 'POST',49				url: 'index.php?' + fileurl50			}).done(function (response) {51				let res = JSON.parse(response);52				if (res.success) {53					MDInstance[MDGrid].readData(1);54				} else {55					alert(alert_arr.Failed);56				}57			});58			return true;59		}60	},61	inlineedit:(ev) => {62		let rowkey = ev.rowKey;63		let modulename = ev.instance.getValue(rowkey, 'record_module');64		let fieldName = ev.columnName;65		let fieldValue = ev.value;66		let recordid = ev.instance.getValue(rowkey, 'record_id') || '';67		let fileurl = 'module=Utilities&action=UtilitiesAjax&file=MasterDetailGridLayoutActions&mdaction=inline_edit&recordid='+recordid+'&rec_module='+modulename+'&fldName='+fieldName+'&fieldValue='+encodeURIComponent(fieldValue);68		if (recordid != '') {69			jQuery.ajax({70				method: 'POST',71				url: 'index.php?' + fileurl72			}).done(function (response) {73				let res = JSON.parse(response);74				if (res.success) {75					ev.instance.readData(1);76					if (ReloadScreenAfterEdit == 1) {77						masterdetailwork.MDReload();78					}79				} else {80					alert(alert_arr.Failed);81				}82			});83		}84	},85	save: (mdgridInstance, module) => {86		const method_prefix = mdgridInstance.substring(6);87		setTimeout(function () {88			if (ReloadScreenAfterEdit == 1) {89				masterdetailwork.MDReload();90			} else {91				MDInstance[mdgridInstance].destroy();92				window['loadMDGrid'+method_prefix]();93			}94		}, 1300);95	},96	MDUpsert: (MDGrid, module, recordid, CurrentRecord = '') => {97		let record = recordid || '';98		if (record!='') {99			record = '&record='+record;100		}101		if (CurrentRecord!='') {102			CurrentRecord = '&MDCurrentRecord='+CurrentRecord;103		} else if (document.getElementById('record')) {104			CurrentRecord = '&MDCurrentRecord='+document.getElementById('record').value;105		}106		let mapname = document.getElementById(MDGrid.substring(6)).dataset.mapname;107		let mdgridinfo = JSON.stringify({108			'name': MDGrid,109			'module': module,110			'mapname': mapname,111		});112		window.open('index.php?module='+module+'&action=EditView&Module_Popup_Edit=1&FILTERFIELDSMAP='+mapname+'&MDGridInfo='+mdgridinfo+record+CurrentRecord, null, cbPopupWindowSettings + ',dependent=yes');113	},114	MDView: (MDGrid, module, recordid) => {115		document.getElementById('status').style.display='inline';116		let mapname = document.getElementById(MDGrid.substring(6)).dataset.mapname;117		jQuery.ajax({118			method:'POST',119			url:'index.php?module='+module+'&action=DetailView&Module_Popup_Edit=1&FILTERFIELDSMAP='+mapname+'&record='+recordid120		}).done(function (response) {121			document.getElementById('status').style.display='none';122			document.getElementById('qcform').style.display='inline';123			document.getElementById('qcform').innerHTML = response;124			var btnbar = document.querySelector('ul[name="cbHeaderButtonGroup"]');125			btnbar.innerHTML = `126			<button type="button" class="slds-button slds-button_icon-error slds-button__icon_large" onclick="hide('qcform');" title="${alert_arr['LBL_CLOSE_TITLE']}">127				<svg class="slds-button__icon" aria-hidden="true">128					<use xlink:href="include/LD/assets/icons/utility-sprite/svg/symbols.svg#close"></use>129				</svg>130			</button>`;131			jQuery('#qcform').draggable();132			vtlib_executeJavascriptInElement(document.getElementById('qcform'));133		});134	},135	MDReload: () => {136		VtigerJS_DialogBox.block();137		const queryString = window.location.search;138		const urlParams = new URLSearchParams(queryString);139		const crmId = urlParams.get('record');140		const data = {141			'fldName' : '',142			'fieldValue' : ''143		};144		const url = `file=DetailViewAjax&module=${gVTModule}&action=${gVTModule}Ajax&record=${crmId}&recordid=${crmId}&ajxaction=DETAILVIEWLOAD`;145		jQuery.ajax({146			method: 'POST',147			url: 'index.php?' + url,148			data : data149		}).done(function (response) {150			if (response.indexOf(':#:SUCCESS')>-1) {151				const result = response.split(':#:');152				if (result[2] != null) {153					const target = document.getElementsByClassName('detailview_wrapper_table')[0];154					target.innerHTML = result[2];155					vtlib_executeJavascriptInElement(target);156				}157				VtigerJS_DialogBox.hidebusy();158			}159			VtigerJS_DialogBox.unblock();160		});161	},162};163class mdActionRender {164	constructor(props) {165		let el;166		let rowKey = props.rowKey;167		let permissions = props.grid.getValue(rowKey, 'record_permissions');168		let recordid = props.grid.getValue(rowKey, 'record_id') || '';169		let module = props.grid.getValue(rowKey, 'record_module');170		el = document.createElement('span');171		let actions = '<div class="slds-button-group" role="group">';172		if (props.columnInfo.renderer.options.moveup) {173			actions += `174			<button class="slds-button slds-button_icon slds-button_icon-border-filled" onclick="masterdetailwork.moveup('mdgrid${props.grid.el.id}', ${recordid}, '${module}', ${rowKey});" title="${alert_arr['MoveUp']}">175				<svg class="slds-button__icon" aria-hidden="true">176					<use xlink:href="include/LD/assets/icons/utility-sprite/svg/symbols.svg#up"></use>177				</svg>178			</button>`;179		}180		if (props.columnInfo.renderer.options.movedown) {181			actions += `182			<button class="slds-button slds-button_icon slds-button_icon-border-filled" onclick="masterdetailwork.movedown('mdgrid${props.grid.el.id}', ${recordid}, '${module}', ${rowKey});" title="${alert_arr['MoveDown']}">183				<svg class="slds-button__icon" aria-hidden="true">184					<use xlink:href="include/LD/assets/icons/utility-sprite/svg/symbols.svg#down"></use>185				</svg>186			</button>`;187		}188		if (props.columnInfo.renderer.options.edit && permissions.edit == 'yes') {189			actions += `190			<button class="slds-button slds-button_icon slds-button_icon-border-filled" onclick="masterdetailwork.MDUpsert('mdgrid${props.grid.el.id}', '${module}', ${recordid});" title="${alert_arr['JSLBL_Edit']}">191				<svg class="slds-button__icon" aria-hidden="true">192					<use xlink:href="include/LD/assets/icons/utility-sprite/svg/symbols.svg#edit"></use>193				</svg>194			</button>`;195		}196		if (props.columnInfo.renderer.options.delete && permissions.delete == 'yes') {197			actions += `198			<button class="slds-button slds-button_icon slds-button_icon-border-filled" onclick="masterdetailwork.delete('mdgrid${props.grid.el.id}', '${module}', ${recordid});" title="${alert_arr['JSLBL_Delete']}">199				<svg class="slds-button__icon" aria-hidden="true">200					<use xlink:href="include/LD/assets/icons/utility-sprite/svg/symbols.svg#delete"></use>201				</svg>202			</button>`;203		}204		actions += '</div>';205		el.innerHTML = actions;206		this.el = el;207		this.render(props);208	}209	getElement() {210		return this.el;211	}212	render(props) {213		this.el.value = String(props.value);214	}215}216class mdLinkRender {217	constructor(props) {218		let el;219		let rowKey = props.rowKey;220		let columnName = props.columnInfo.name;221		let fieldValue = props.grid.getValue(rowKey, `${columnName}_attributes`);222		if (fieldValue.length > 0) {223			el = document.createElement('a');224			el.href = fieldValue[0].mdLink;225			if (fieldValue[0].mdTarget) {226				el.target = fieldValue[0].mdTarget;227			}228			el.innerHTML = String(fieldValue[0].mdValue);229		} else {230			el = document.createElement('span');231			el.innerHTML = String(props.value);232		}233		this.el = el;234		this.render(props);235	}236	getElement() {237		return this.el;238	}239	render(props) {240		this.el.value = String(props.value);241	}...markdown.js
Source:markdown.js  
1import $ from 'jquery';2import markdownit from 'markdown-it';3import attr from 'markdown-it-attrs';4import sub from 'markdown-it-sub';5import sup from 'markdown-it-sup';6import footnote from 'markdown-it-footnote';7import figures from 'markdown-it-implicit-figures';8import taskcheckbox from 'markdown-it-task-checkbox';9import deflist from 'markdown-it-deflist';10import emoji from 'markdown-it-emoji';11import mathjax from 'markdown-it-mathjax';12import abbr from 'markdown-it-abbr';13import container from 'markdown-it-container';14import _ from 'lodash';15import prism from './prism';16import preprocessor from './preprocessor';17import Reference from './reference';18import abbrev from './abbrev';19import util from './util';20import utilJq from './util-jq';21function markdown(str, opts) {22  let mdStr = preprocessor(str);23  const mdOpts = markdown.options(opts);24  let md = markdown.md;25  if (mdOpts && !_.isEmpty(mdOpts)) {26    md = markdown.parser(mdOpts);27  }28  // ensure that defined references have precedence29  // over wiki references30  const env = markdown.env({31    references: Reference.extractReferencesFromMarkdown(mdStr)32  });33  mdStr = md.render(mdStr, env);34  mdStr = mdStr.trim();35  // mdStr = markdown.highlightInline(mdStr).trim();36  if (mdOpts && mdOpts.inline && mdStr.match(/^<p>/) && mdStr.match(/<\/p>$/)) {37    const beg = '<p>'.length;38    const end = '</p>'.length;39    mdStr = mdStr.substring(beg, mdStr.length - end);40  }41  return mdStr;42}43markdown.env = function(env) {44  const mdEnv = env || {};45  mdEnv.references = mdEnv.references || {};46  mdEnv.abbreviations = mdEnv.abbreviations || {};47  mdEnv.references = _.assign({}, Reference.getReferences(), mdEnv.references);48  mdEnv.references = Reference.removeUnsafeReferences(mdEnv.references);49  mdEnv.abbreviations = _.assign({}, abbrev.getAbbreviations(), mdEnv.abbreviations);50  return mdEnv;51};52// markdown.highlightBlock = function(str, lang) {53//   if (lang && hljs.getLanguage(lang)) {54//     try {55//       return hljs.highlight(lang, str, true).value;56//     } catch (__) {}57//   }58//   return '';59// };60// markdown.highlightInline = function(str) {61//   return utilJq.dojQuery(str, function(body) {62//     body.find('code[class]').each(function() {63//       let code = $(this);64//       let pre = code.parent();65//       if (pre.prop('tagName') === 'PRE') {66//         return;67//       }68//       let lang = code.attr('class');69//       if (lang && hljs.getLanguage(lang)) {70//         try {71//           code.removeClass(lang);72//           code.addClass('language-' + lang);73//           let str = code.text().trim();74//           let html = hljs.highlight(lang, str, false).value;75//           code.html(html);76//         } catch (__) {}77//       }78//     });79//   });80// };81markdown.defaults = {82  html: true, // Enable HTML tags in source83  breaks: true, // Convert '\n' in paragraphs into <br>84  linkify: true, // Autoconvert URL-like text to links85  // Enable some language-neutral replacement + quotes beautification86  typographer: true87  // Highlighter function. Should return escaped HTML,88  // or '' if the source string is not changed and should be escaped externally.89  // If result starts with <pre..., internal wrapper is skipped.90  // highlight: markdown.highlightBlock91};92markdown.options = function(opts) {93  const mdOpts = opts || {};94  const options = {};95  if (Object.prototype.hasOwnProperty.call(mdOpts, 'hard_line_breaks')) {96    options.breaks = mdOpts.hard_line_breaks;97  }98  if (Object.prototype.hasOwnProperty.call(mdOpts, 'breaks')) {99    options.breaks = mdOpts.breaks;100  }101  if (Object.prototype.hasOwnProperty.call(mdOpts, 'autolink_bare_uris')) {102    options.linkify = mdOpts.autolink_bare_uris;103  }104  if (Object.prototype.hasOwnProperty.call(mdOpts, 'linkify')) {105    options.linkify = mdOpts.linkify;106  }107  if (Object.prototype.hasOwnProperty.call(mdOpts, 'smart')) {108    options.typographer = mdOpts.smart;109  }110  if (Object.prototype.hasOwnProperty.call(mdOpts, 'typographer')) {111    options.typographer = mdOpts.typographer;112  }113  if (Object.prototype.hasOwnProperty.call(mdOpts, 'emoji')) {114    options.emoji = mdOpts.emoji;115  }116  if (Object.prototype.hasOwnProperty.call(mdOpts, 'mathjax')) {117    options.mathjax = mdOpts.mathjax;118  }119  if (Object.prototype.hasOwnProperty.call(mdOpts, 'inline')) {120    options.inline = mdOpts.inline;121  }122  return options;123};124markdown.parser = function(opts) {125  let mdOpts = opts || {};126  mdOpts = _.assign({}, markdown.defaults, mdOpts);127  return markdown.plugins(markdownit(mdOpts), mdOpts);128};129markdown.plugins = function(md, opts) {130  const mdOpts = opts || {};131  let mdInstance = md.use(figures, { figcaption: true });132  // if (opts.mathjax !== true) {133  mdInstance = mdInstance.use(attr);134  // }135  mdInstance = mdInstance136    .use(sub)137    .use(sup)138    .use(footnote)139    .use(taskcheckbox, { disabled: false })140    .use(deflist);141  mdInstance = markdown.containerPlugin(mdInstance);142  if (mdOpts.emoji === true) {143    mdInstance = mdInstance.use(emoji);144    mdInstance.renderer.rules.emoji = function(token, idx) {145      return '<span class="emoji emoji_' + token[idx].markup + '">' + token[idx].content + '</span>';146    };147  }148  if (mdOpts.mathjax === true) {149    mdInstance = mdInstance.use(mathjax());150  }151  mdInstance = mdInstance.use(abbr);152  mdInstance = mdInstance.use(prism);153  return mdInstance;154};155markdown.containerPlugin = function(md) {156  const renderContainer = function(bsClass, title) {157    return function(tokens, idx) {158      const info = tokens[idx].info.trim();159      const bsClassName = bsClass || info.toLowerCase();160      const titleStr = title || _.capitalize(info);161      const isOpeningTag = tokens[idx].nesting === 1;162      return isOpeningTag163        ? '<div class="bs-callout bs-callout-' + bsClassName + '"><h4>' + titleStr + '</h4>\n'164        : '</div>\n';165    };166  };167  return md168    .use(container, 'default', { render: renderContainer() })169    .use(container, 'primary', { render: renderContainer() })170    .use(container, 'success', { render: renderContainer() })171    .use(container, 'info', { render: renderContainer() })172    .use(container, 'warning', { render: renderContainer() })173    .use(container, 'danger', { render: renderContainer() })174    .use(container, 'viktig', { render: renderContainer('warning') })175    .use(container, 'advarsel', { render: renderContainer('danger') })176    .use(container, 'note', { render: renderContainer('info') });177};178markdown.inline = function(str) {179  return markdown(str, { inline: true });180};181markdown.toText = function(str) {182  const html = markdown.inline(str);183  return utilJq.htmlToText(html);184};185markdown.md = markdown.parser();...document-control.js
Source:document-control.js  
1import boxApi from "./boxapi.js";2import oktaApi from "./oktaApi.js";3import config from "./config.js";4const main = async () => {5	// Because dates are converted to ISO8601 strings which is in UTC, they need correction with an timezone offset6	const date = new Date()7	const offSet = date.getTimezoneOffset()8	const firstDayUTC = new Date(date.getFullYear(), date.getMonth() + (config.notifyNumberOfMonthsAhead), 1, 0, date.getHours() + (offSet * -1),0);9	const lastDayUTC = new Date(date.getFullYear(), date.getMonth() + (config.notifyNumberOfMonthsAhead + 1), 0, 0, date.getHours() + (offSet * -1), 0);10	const mdfilters = JSON.stringify([11		{12			"scope":"enterprise_844815493",13			"templateKey":"documentControl",14			"filters":{15				"expirationDate": {16					"gt": `${firstDayUTC.toISOString()}`,17					"lt": `${lastDayUTC.toISOString()}`,18				}19			}20		}21	])22	const response = await boxApi.get('search',{params: {23		mdfilters: mdfilters24	}})25	console.log(`Searching Box for documents expiring between ${getReadableDate(firstDayUTC)} and ${getReadableDate(lastDayUTC)}`)26	const result = await Promise.all(response.data.entries.map(async doc => {27		const boxResponse = await boxApi.get(`files/${doc.id}/metadata`)28		const mdInstance = boxResponse.data.entries.find(entry => entry.$template == 'documentControl')29		30		const oktaResponse = await oktaApi.get('users',{params: {31			search: `profile.NIDRole eq \"${mdInstance.ownership}\"`32		}})33		return {34			id: doc.id,35			name: doc.name,36			approvalDate: mdInstance.approvalDate,37			expirationDate: mdInstance.expirationDate,38			ownership: mdInstance.ownership,39			users: oktaResponse.data.map(user => {40				return user.profile.email41			})42		}	 43	}))44	result.map(async doc => {45		try {46			47			const { data : { id : taskId }} = await boxApi.post(`tasks`,{48				action: "complete",49				completion_rule: "any_assignee",50				due_at: doc.expirationDate, //new Date(doc.expirationDate).setHours(new Date(doc.expirationDate).getHours + offSet).toISOString(),51				item: {52					id: doc.id,53					type: "file"54				},55				message: `This document is due for updating since it's expiring at ${getReadableDate(doc.expirationDate)}. \n\nPlease review and update accordingly by following the Document Control Policy guidelines.`56				57			})58			59			doc.users.map(async user => {60				const {data} = await boxApi.post(`task_assignments`, {61					task: { 62						id: taskId,63						type: "task"64					},65					assign_to: {66						login: user67					}68				})69		70			})71			console.log(`A task was created for document ${doc.id} and was assigned to ${doc.users.join(", ")}`)72		} catch(error) {73			console.log((error.data !== undefined) ? error.data : error)74		}75	})76}77const getReadableDate = (dt) => {78	const date = new Date(dt)79	return `${date.getMonth()+1}/${date.getDate()}/${date.getFullYear()}`80}...Using AI Code Generation
1console.log(mdInstance.maxProfit([7,1,5,3,6,4]));2class BestTimeToBuyAndSellStockIII {3  maxProfit(prices) {4    let profit1 = 0;5    let profit2 = 0;6    let minPrice1 = Number.MAX_VALUE;7    let minPrice2 = Number.MAX_VALUE;8    for (let i = 0; i < prices.length; i++) {9      minPrice1 = Math.min(minPrice1, prices[i]);10      profit1 = Math.max(profit1, prices[i] - minPrice1);11      minPrice2 = Math.min(minPrice2, prices[i] - profit1);12      profit2 = Math.max(profit2, prices[i] - minPrice2);13    }14    return profit2;15  }16}17module.exports = BestTimeToBuyAndSellStockIII;18console.log(mdInstance.maxProfit([3,3,5,0,0,3,1,4]));19class BestTimeToBuyAndSellStockIV {20  maxProfit(k, prices) {21    if (k >= prices.length / 2) {22      return this.quickSolve(prices);23    }24    let dp = new Array(k + 1).fill(0).map(() => new Array(prices.length).fill(0));25    for (let i = 1; i <= k; i++) {26      let tempMax = -prices[0];27      for (let j = 1; j < prices.length; j++) {28        dp[i][j] = Math.max(dp[i][j - 1], prices[j] + tempMax);29        tempMax = Math.max(tempMax, dp[i - 1][j - 1] - prices[j]);30      }31    }Using AI Code Generation
1var BestClass = require('./bestclass.js');2var mdInstance = new BestClass();3mdInstance.mdInstance();4var mdInstance = function() {5    this.mdInstance = function() {6        console.log('mdInstance');7    }8}9module.exports = mdInstance;10import BestClass from './bestclass';11let mdInstance = new BestClass();12mdInstance.mdInstance();13export default class BestClass {14    mdInstance() {15        console.log('mdInstance');16    }17}Using AI Code Generation
1const BestMd = require('best-md');2const bestMd = new BestMd();3const md = bestMd.mdInstance();4const html = md.render('# Hello World');5console.log(html);6### BestMd()7#### .mdInstance()Using AI Code Generation
1const bestMd = require('best-md')2const mdInstance = bestMd.mdInstance()3const fs = require('fs')4const path = require('path')5const {promisify} = require('util')6const writeFile = promisify(fs.writeFile)7const readFile = promisify(fs.readFile)8const file = path.join(dirname, 'test.md')9const file2 = path.join(dirname, 'test2.md')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!!
