Best JavaScript code snippet using wpt
products.js
Source:products.js
1let products = [];2// Utils3function roundToDecimalPlaces(num) {4 return num.toFixed(2);5}6function isEmpty(val) {7 return val !== "" && val !== undefined && val.length > 0 && val !== null;8}9// Get All Products10async function getAllProducts() {11 const result = await fetch("./products.json");12 return await result.json();13}14async function loadProductsToTable(productsParam) {15 const tbody = document.querySelector("tbody");16 if (!productsParam || productsParam.length < 1) {17 products = await getAllProducts();18 } else {19 products = productsParam;20 }21 let rows = "";22 while (tbody.firstChild) {23 tbody.removeChild(tbody.firstChild);24 }25 for (product of products) {26 rows += ` <tr>27 <td>${product.rowNumber}</td>28 <td>${product.category}</td> 29 <td>${product.productName}</td> 30 <td>${product.price}</td>31 <td>${product.manufacturer}</td>32 <td>${product.productionDate}</td>33 </tr>`;34 }35 tbody.insertAdjacentHTML("beforeend", rows);36}37// Total Quantity38async function getTotalQuantity() {39 let products = await getAllProducts();40 return products.length;41}42async function displayQuantity() {43 const totalQuantity = document.querySelector(".total_quantity");44 totalQuantity.innerText = await getTotalQuantity();45}46// Total Cost47async function getTotalCost() {48 let products = await getAllProducts();49 const totalCost = products.reduce((a, b) => ({50 price: parseFloat(a.price) + parseFloat(b.price),51 }));52 return totalCost;53}54async function displayTotalCost() {55 const totalCostWrapper = document.querySelector(".total_cost_wrapper");56 let totalCost = await getTotalCost();57 let spanElement = document.createElement("span");58 spanElement.innerText = roundToDecimalPlaces(totalCost.price);59 totalCostWrapper.appendChild(spanElement);60}61// AveragePrice62async function getAveragePrice() {63 let totalCost = await getTotalCost();64 let totalQuantity = await getTotalQuantity();65 let averagePrice = totalCost.price / totalQuantity;66 return averagePrice;67}68async function displayAveragePRice() {69 const average_price = document.querySelector(".average_price");70 let spanElement = document.createElement("span");71 spanElement.innerText = roundToDecimalPlaces(await getAveragePrice());72 average_price.appendChild(spanElement);73}74// Max Price75async function getMaxPrice() {76 let products = await getAllProducts();77 let result = products.reduce(function (a, b) {78 return a.price > b.price ? a : b;79 }, {});80 return result;81}82async function displayMaxPrice() {83 const maxPrice = document.querySelector(".max_price");84 const product = await getMaxPrice();85 let priceElement = document.createElement("span");86 priceElement.innerText = roundToDecimalPlaces(parseFloat(product.price));87 maxPrice.appendChild(priceElement);88 let productNameElement = document.createElement("span");89 productNameElement.innerText = product.productName;90 maxPrice.appendChild(productNameElement);91}92// Max Price93async function getMinPrice() {94 let products = await getAllProducts();95 let result = products.reduce(function (a, b) {96 return a.price < b.price ? a : b;97 }, {});98 return result;99}100async function displayMinPrice() {101 const minPrice = document.querySelector(".min_price");102 const product = await getMinPrice();103 let priceElement = document.createElement("span");104 priceElement.innerText = roundToDecimalPlaces(parseFloat(product.price));105 minPrice.appendChild(priceElement);106 let productNameElement = document.createElement("span");107 productNameElement.innerText = product.productName;108 minPrice.appendChild(productNameElement);109}110// Categories111async function getAllCategories() {112 let products = await getAllProducts();113 let productsCategories = products.map(function (a) {114 return a.category;115 }, {});116 var uniqueCategories = [...new Set(productsCategories)];117 return uniqueCategories;118}119async function displayAllCategories() {120 const categoryBoxes = document.querySelector(".category_boxes");121 const categories = await getAllCategories();122 let categoriesHtml = "";123 categories.forEach((category) => {124 categoriesHtml += `<div>125 <input type="checkbox" id="${category}" name="${category}" value="${category}">126 <label for="${category}">${category}</label>127 </div>`;128 });129 categoryBoxes.insertAdjacentHTML("beforeend", categoriesHtml);130}131// Categories132async function getAllManufacturers() {133 let products = await getAllProducts();134 let productsManaufacturers = products.map(function (a) {135 return a.manufacturer;136 }, {});137 var uniqueManufacturers = [...new Set(productsManaufacturers)];138 return uniqueManufacturers;139}140async function displayAllManufacturers() {141 const manufacturerBoxes = document.querySelector(".manufacturer_boxes");142 const manufacturers = await getAllManufacturers();143 let manufacturersHtml = "";144 manufacturers.forEach((manufacturer) => {145 manufacturersHtml += `<div>146 <input type="checkbox" id="${manufacturer}" name="${manufacturer}" value="${manufacturer}">147 <label for="${manufacturer}">${manufacturer}</label>148 </div>`;149 });150 manufacturerBoxes.insertAdjacentHTML("beforeend", manufacturersHtml);151}152// Sort products153let sortDirection = "asc";154async function sortProducts(products, sortByPropertyName) {155 let sortedProducts = [];156 if (sortDirection === "asc") {157 if (sortByPropertyName === "price" || sortByPropertyName === "rowNumber") {158 sortedProducts = products.sort(159 (a, b) => a[sortByPropertyName] - b[sortByPropertyName]160 );161 } else if (sortByPropertyName === "productionDate") {162 sortedProducts = products.sort(163 (a, b) =>164 new Date(a[sortByPropertyName]) - new Date(b[sortByPropertyName])165 );166 } else {167 sortedProducts = products.sort((a, b) =>168 a[sortByPropertyName].localeCompare(b[sortByPropertyName])169 );170 }171 sortDirection = "desc";172 } else if (sortDirection === "desc") {173 if (sortByPropertyName === "price" || sortByPropertyName === "rowNumber") {174 sortedProducts = products.sort(175 (a, b) => b[sortByPropertyName] - a[sortByPropertyName]176 );177 } else if (sortByPropertyName === "productionDate") {178 sortedProducts = products.sort(179 (a, b) =>180 new Date(b[sortByPropertyName]) - new Date(a[sortByPropertyName])181 );182 } else {183 sortedProducts = products.sort((a, b) =>184 b[sortByPropertyName].localeCompare(a[sortByPropertyName])185 );186 }187 sortDirection = "asc";188 }189 loadProductsToTable(sortedProducts);190}191displayQuantity();192displayTotalCost();193displayAveragePRice();194displayMaxPrice();195displayMinPrice();196displayAllCategories();197displayAllManufacturers();198loadProductsToTable();199let table = document.querySelector("table");200table.addEventListener("click", async (e) => {201 if (e.target.classList.contains("header")) {202 sortProducts(products, e.target.dataset.header);203 }204});205function togglePanel() {206 const sidePanelOptions = document.getElementById("side_panel_options");207 sidePanelOptions.classList.toggle("side_panel_hide");208}209document.getElementById("btn_options").addEventListener("click", (e) => {210 togglePanel();211});212document.querySelector(".close_sidebar").addEventListener("click", (e) => {213 togglePanel();214});215document.getElementById("btn_apply").addEventListener("click", async (e) => {216 e.preventDefault();217 products = await getAllProducts();218 let categoriesChecked = Array.from(219 document.querySelectorAll(".category_boxes input[type='checkbox']:checked")220 ).map((elem) => elem.value);221 let manufacturersChecked = Array.from(222 document.querySelectorAll(223 ".manufacturer_boxes input[type='checkbox']:checked"224 )225 ).map((elem) => elem.value);226 let highestPrice = document.getElementById("txt_highest_price").value;227 let lowestPrice = document.getElementById("txt_lowest_price").value;228 if (!isEmpty(highestPrice) || !lowestPrice) {229 if (isEmpty(highestPrice) && isEmpty(lowestPrice)) {230 alert("Highest Price and Lowest Price must have a value");231 return;232 }233 }234 let searchedProducts = products.filter(235 (product) =>236 categoriesChecked.includes(product.category) ||237 manufacturersChecked.includes(product.manufacturer) ||238 (parseFloat(highestPrice) > parseFloat(product.price) &&239 parseFloat(lowestPrice) < parseFloat(product.price))240 );241 loadProductsToTable(searchedProducts);242 togglePanel();243});244let btnReset = document.getElementById("btn_reset");245btnReset.addEventListener("click", async (e) => {246 products = [];247 products = await getAllProducts();248 document249 .querySelectorAll("input[type=checkbox]")250 .forEach((el) => (el.checked = false));251 document252 .querySelectorAll("input[type=text]")253 .forEach((el) => (el.value = ""));254 loadProductsToTable(products);255 togglePanel();...
Leaderboard.js
Source:Leaderboard.js
...38 this.findAll(`username`);39 break;40 case `battles`:41 thirdColumnIndex = 2;42 this.sortByPropertyName(`fights`, `desc`);43 break;44 case `wins`:45 thirdColumnIndex = 3;46 this.sortByPropertyName(`wins`, `desc`);47 break;48 case `losses`:49 thirdColumnIndex = 4;50 this.sortByPropertyName(`losses`, `desc`);51 break;52 case `winPercentage`:53 thirdColumnIndex = 5;54 this.findAll(`percentage`);55 break;56 case `prestige`:57 thirdColumnIndex = 6;58 this.sortByPropertyName(`prestige`, `desc`);59 break;60 case `rosterLength`:61 thirdColumnIndex = 7;62 this.findAll(`roster`);63 break;64 default:65 thirdColumnIndex = 6;66 this.getTopScorers();67 }68 const headerColumns = this.state.headerColumns;69 headerColumns.pop();70 headerColumns.push(this.headerCells[thirdColumnIndex]);71 this.setState({72 headerColumns: headerColumns,...
helpers.ts
Source:helpers.ts
1import { Injectable } from '@angular/core';2// MODELS3import { LookUpItem, LookUpItemRaw, SortOrder } from '../../models/models';4@Injectable()5export class MultiLevelSelectHelpers {6 public buildHierarchicalLookUp(lookups: LookUpItemRaw[]): LookUpItem[] {7 if (lookups && lookups.length > 0) {8 const _lookupsTree: LookUpItem[] = [];9 const addChildren = (parent: LookUpItem) => {10 lookups.forEach((value: LookUpItemRaw) => {11 if (value.parent_id === parent.id) {12 const _child: LookUpItem = { id: value.id, parentId: value.parent_id, name: value.name, children: [] };13 parent.children.push(_child);14 addChildren(_child);15 }16 });17 };18 lookups.forEach((value: LookUpItemRaw) => {19 if (value.parent_id == null) {20 const _topParent: LookUpItem = { id: value.id, parentId: null, name: value.name, children: [] };21 _lookupsTree.push(_topParent);22 addChildren(_topParent);23 }24 });25 return _lookupsTree;26 } else {27 return [];28 }29 }30 public sortHierarchicalLookUpAsTreeInAscOrder(hierarchicalLookUpAsTree: LookUpItem[], sortBy: SortOrder): void {31 let sortByPropertyName = null;32 let valueBeingSortedStrings = false;33 if (sortBy === SortOrder.ById) {34 // sort by id in asc order35 sortByPropertyName = 'id';36 } else if (sortBy === SortOrder.Alphabetical) {37 // sort by name in asc order38 sortByPropertyName = 'name';39 valueBeingSortedStrings = true;40 } else {41 throw new Error(`Helpers provider: not supported sortBy param is provided. sortBy: ${JSON.stringify(sortBy)}`);42 }43 const sortByFn = (a, b) => {44 const aValue = valueBeingSortedStrings ? a[sortByPropertyName].toLowerCase() : a[sortByPropertyName];45 const bValue = valueBeingSortedStrings ? b[sortByPropertyName].toLowerCase() : b[sortByPropertyName];46 // a is less than b by some ordering criterion47 if (aValue < bValue) {48 return -1;49 }50 // a is greater than b by the ordering criterion51 if (aValue > bValue) {52 return 1;53 }54 // a must be equal to b55 return 0;56 };57 const sortChildren = (childrenToSort: LookUpItem[]) => {58 childrenToSort.sort(sortByFn);59 childrenToSort.forEach((value: LookUpItem) => {60 if (value.children && value.children.length > 0) {61 sortChildren(value.children);62 }63 });64 };65 hierarchicalLookUpAsTree.sort(sortByFn);66 hierarchicalLookUpAsTree.forEach((value: LookUpItem) => {67 if (value.children && value.children.length > 0) {68 sortChildren(value.children);69 }70 });71 }...
Using AI Code Generation
1var wpt = require('wpt');2 {name: 'John', age: 25},3 {name: 'Peter', age: 24},4 {name: 'Mike', age: 24},5 {name: 'John', age: 24}6];7var sortedData = wpt.sortByPropertyName(data, 'name');8console.log(sortedData);9var wpt = require('wpt');10 {name: 'John', age: 25},11 {name: 'Peter', age: 24},12 {name: 'Mike', age: 24},13 {name: 'John', age: 24}14];15var sortedData = wpt.sortByPropertyName(data, 'age');16console.log(sortedData);17The MIT License (MIT)
Using AI Code Generation
1var wptools = require('wptools');2var array = [];3var obj = {name: 'foo', age: 10};4array.push(obj);5obj = {name: 'bar', age: 30};6array.push(obj);7obj = {name: 'baz', age: 20};8array.push(obj);9wptools.sortByPropertyName(array, 'age');10var wptools = require('wptools');11var array = [];12var obj = {name: 'foo', age: 10};13array.push(obj);14obj = {name: 'bar', age: 30};15array.push(obj);16obj = {name: 'baz', age: 20};17array.push(obj);18wptools.sortByPropertyName(array, 'age', true);19var wptools = require('wptools');20var array = [];21var obj = {name: 'foo', age: 10};22array.push(obj);23obj = {name: 'bar', age: 30};24array.push(obj);25obj = {name: 'baz', age: 20};26array.push(obj);27wptools.sortByPropertyName(array, 'name');28var wptools = require('wptools');29var array = [];30var obj = {name: 'foo', age: 10};31array.push(obj);32obj = {name: 'bar', age: 30};33array.push(obj);34obj = {name: 'baz', age: 20};35array.push(obj);
Using AI Code Generation
1var arr = [{name: "John", age: 26}, {name: "Sally", age: 24}, {name: "Bob", age: 31}];2var sorted = sortByPropertyName(arr, "name");3var arr = [{name: "John", age: 26}, {name: "Sally", age: 24}, {name: "Bob", age: 31}];4var sorted = sortByPropertyName(arr, "age");5var arr = [{name: "John", age: 26}, {name: "Sally", age: 24}, {name: "Bob", age: 31}];6var sorted = sortByPropertyName(arr, "name");7var arr = [{name: "John", age: 26}, {name: "Sally", age: 24}, {name: "Bob", age: 31}];8var sorted = sortByPropertyName(arr, "age");9var arr = [{name: "John", age: 26}, {name: "Sally", age: 24}, {name: "Bob", age: 31}];10var sorted = sortByPropertyName(arr, "name");
Using AI Code Generation
1var wptools = require('wptools');2var wp = wptools.page('Barack Obama');3wp.get(function(err, resp) {4 console.log(resp);5 console.log(resp.sortByPropertyName('birth_date'));6});7var wptools = require('wptools');8var wp = wptools.page('Barack Obama');9wp.get(function(err, resp) {10 console.log(resp);11 console.log(resp.sortByPropertyName('death_date'));12});
Using AI Code Generation
1var wpt = require('wpt');2var arr = [{name:'A',age:10},{name:'B',age:20},{name:'C',age:30}];3var sortedArr = wpt.utils.sortByPropertyName(arr,'age');4console.log(sortedArr);5var wpt = require('wpt');6var arr = [{name:'A',age:10},{name:'B',age:20},{name: 'C',age:30}];7var sortedArr = wpt.utils.sortByPropertyName(arr,'age',false);8console.log(sortedArr);9var wpt = require('wpt');10var arr = [{name:'A',age:10},{name:'B',age:20},{name: 'C',age:30}];11var sortedArr = wpt.utils.sortByPropertyName(arr,'age',true);12console.log(sortedArr);13var wpt = require('wpt');14var arr = [{name:'A',age:10},{name:'B',age:20},{name: 'C',age:30}];15var sortedArr = wpt.utils.sortByPropertyName(arr,'age',true);16console.log(sortedArr);17var wpt = require('wpt');18var arr = [{name:'A',age:10},{name:'B',age:20},{name: 'C',age:30}];19var sortedArr = wpt.utils.sortByPropertyName(arr,'name',
Using AI Code Generation
1var wpt=require('wpt');2var data=[{name:'John',age:25},{name:'Jane',age:24}];3var sortedData=wpt.sortByPropertyName(data,'age',true);4console.log(sortedData);5var wpt=require('wpt');6var data=[{name:'John',age:25},{name:'Jane',age:24}];7var sortedData=wpt.sortByPropertyName(data,'age',false);8console.log(sortedData);9var wpt=require('wpt');10var data=[{name:'John',age:25},{name:'Jane',age:24}];11var sortedData=wpt.sortByPropertyName(data,'age',true);12console.log(sortedData);13var wpt=require('wpt');14var data=[{name:'John',age:25},{name:'Jane',age:24}];15var sortedData=wpt.sortByPropertyName(data,'age',false);16console.log(sortedData);17var wpt=require('wpt');18var data=[{name:'John',age:25},{name:'Jane',age:24}];19var sortedData=wpt.sortByPropertyName(data,'age',true);20console.log(sortedData);21var wpt=require('wpt');22var data=[{name:'John',age:25},{name:'Jane',age:24}];23var sortedData=wpt.sortByPropertyName(data,'age',false);24console.log(sortedData);
Using AI Code Generation
1var wpt = require('wpt'); 2var myArray = [ {name: 'John', age: 23}, {name: 'Jane', age: 21} ];3var sortedArray = wpt.sortByPropertyName(myArray, 'age');4console.log(sortedArray);5var wpt = require('wpt'); 6var myArray = [ {name: 'John', age: 23}, {name: 'Jane', age: 21} ];7var sortedArray = wpt.sortByPropertyName(myArray, 'age', 'desc');8console.log(sortedArray);9var wpt = require('wpt'); 10var myArray = [ {name: 'John', age: 23}, {name: 'Jane', age: 21} ];11var sortedArray = wpt.sortByPropertyName(myArray, 'age', 'asc');12console.log(sortedArray);13var wpt = require('wpt'); 14var myArray = [ {name: 'John', age: 23}, {name: 'Jane', age: 21} ];15var sortedArray = wpt.sortByPropertyName(myArray, 'age', 'xyz');16console.log(sortedArray);17var wpt = require('wpt'); 18var myArray = [ {name: 'John', age: 23}, {name: 'Jane', age: 21} ];19var sortedArray = wpt.sortByPropertyName(myArray, 'age', 1);20console.log(sortedArray);
Using AI Code Generation
1var utils = require('wptUtils');2 {name:'A',age:23},3 {name:'B',age:21},4 {name:'C',age:22}5];6var arr2 = utils.sortByPropertyName(arr,'age');7console.log(arr2);8var utils = require('wptUtils');9 {name:'A',age:23},10 {name:'B',age:21},11 {name:'C',age:22}12];13var arr2 = utils.sortByPropertyNames(arr,['age','name']);14console.log(arr2);15var utils = require('wptUtils');16 {name:'A',age:23},17 {name:'B',age:21},18 {name:'C',age:22}19];20var arr2 = utils.sortByPropertyNames(arr,['age','name'],[false,true]);21console.log(arr2);22var utils = require('wptUtils');23 {name:'A',age:23},24 {name:'B',age:21},25 {name:'C',age:22}26];27var arr2 = utils.sortByPropertyNames(arr,['age','name'],[false,true],['number','string']);28console.log(arr2);
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!!