How i can optimize this code, whithout creating variable `a`? - javascript

Help to optimize below functions, whithout creating variable a
getFieldsGroups(){
let a = [];
if(this.activeTab.fieldsGroupName === ''){
this.activeTab = {
groupIndex: 0,
subgroupIndex: 0,
fieldsGroupName: this.groups[0][0].name
}
}
this.groups.forEach((group, groupIndex) => {
group.forEach((fieldsGroup, fieldsGroupIndex) => {
if(
groupIndex == this.activeTab.groupIndex &&
fieldsGroup.name == this.activeTab.fieldsGroupName
){
a.push(fieldsGroup);
}
})
})
return a.length == 1 ? [] : a;
}
getFields(){
let a;
this.groups.forEach((group, groupIndex) => {
group.forEach((fieldsGroup, fieldsGroupIndex) => {
if(
groupIndex == this.activeTab.groupIndex &&
fieldsGroup.name == this.activeTab.fieldsGroupName
){
if(this.activeFieldsGroup.name === '' && fieldsGroup.name === this.activeTab.fieldsGroupName){
a = group.filter(_fieldsGroup => _fieldsGroup.name === this.activeTab.fieldsGroupName)[0];
}else if(fieldsGroup.label == this.activeFieldsGroup.label){
a = fieldsGroup;
}
}
})
})
return a.fields.length == 1 ? [] : a.fields;
},

Related

I'm trying to make an interactive bot with automatic messages on whatsapp-web.js, but it only works with one person at a time

How do I make a pos++ only when it's the right person?
I believe the error is because the code makes a pos++ for other people and that's why it interferes with the code.
I just started programming so it can be an easy thing to solve and I don't know how to do it.
const qrcode = require('qrcode-terminal');
const { Client } = require('whatsapp-web.js');
const client = new Client();
client.on('qr', qr => {
qrcode.generate(qr, { small: true });
});
client.on('ready', () => {
console.log('Client is ready!');
});
client.initialize();
var pos = 0
var tentativa = 0
var aviso = 0
client.on('message', message => {
if (message.body === '2' && message.from === message.from && pos == 0) {
client.sendMessage(message.from, `👨‍💻 `);
}
else if (message.body === '1' && pos == 0) {
client.sendMessage(message.from, ` ... ?`);
}
else if (message.body === '1' && message.from === message.from && pos == 1) {
client.sendMessage(message.from, ` 😁 `)
}
else if (message.body === '2' && message.from === message.from &&tentativa == 0 && pos == 1) {
client.sendMessage(message.from, `ok`)
client.sendMessage(message.from, `ok`)
}
else if (message.body === '1' && message.from === message.from && pos == 2) {
client.sendMessage(message.from, ` 😁
`)
}
else if (message.body === '2' && message.from === message.from && pos == 2) {
client.sendMessage(message.from, `😁 `)
}
if (message.body === '2') {
tentativa++
}
if (message.body === '0') {
pos = 0
tentativa = 0
aviso = 0
}
});
client.on('message', message => {
if (message.body.length == 11 && Number(message.body) == parseInt(message.body)) {
client.sendMessage(message.from, `👨‍💻 `);
function cpfs() {
const chatId = "55" + 1112312312 + "#c.us";
client.sendMessage(chatId, message.body);
};
cpfs()
}
else if (message.body !== '1' && message.body !== '2' && aviso == 0) {
client.sendMessage(message.from, `🤖 `);
}
aviso++
})

Render text depending on matching API Results - Axios/JS

I have this working, but it does consume quite a lot of space.
I'm wondering if there is way to refactor it more, matching API results with a smaller refactored condition, perhaps?
axios.js
import axios from 'axios';
export const Models = () => {
return axios.get('data/cars.json')
.then(response => {
return response.data
})
}
file.js
import { Models } from './axios';
let carModels = Models();
carModels.then((result) => {
var i, j, match;
match = false;
for (i = 0; i < result.length; i++) {
for (j = 0; j < result[i].countries.length; j++) {
if (result[i].countries[j].price == price &&
result[i].color == color &&
result[i].brand == brand &&
result[i].model == model &&
result[i].speed == speed)
{
match = true;
return document.querySelector('#brandTitle').textContent = result[i].brand;
}
}
}
if (match == false) {
console.log('No match found.');
}
})
you can use some() that will make sure to terminate the loop as conditions met
carModels.then(result => {
var i, j, match;
match = false;
for (i = 0; i < result.length; i++) {
match = result[i].countries.some(country => {
if (
country.price == price &&
result[i].color == color &&
result[i].brand == brand &&
result[i].model == model &&
result[i].speed == speed
) {
document.querySelector('#brandTitle').textContent = result[i].brand;
return;
}
});
}
if (match == false) {
console.log('No match found.');
}
});
to make more efficient you can use some on parent loop also
carModels.then(result => {
var match;
match = false;
result.some(res => {
match = result[i].countries.some(country => {
if (
country.price == price &&
res.color == color &&
res.brand == brand &&
res.model == model &&
res.speed == speed
) {
document.querySelector('#brandTitle').textContent = res.brand;
return;
}
});
if (match) {
return;
}
});
if (match == false) {
console.log('No match found.');
}
});

How to optimize multiple filter?

I have big search panel with filters
In the computed section I use the next code
computed: {
filteredItems() {
if (this.activeFilter && this.activeFilter != 'all') {
return this.items[this.activeFilter]
.filter(item => item.name.toLowerCase().indexOf(this.search.toLowerCase()) !== -1)
.filter(item => item.itemLevel >= this.minLvl && item.itemLevel <= this.maxLvl);
} else {
let all = [];
let i;
if (this.items) {
for (i = 0; i < this.filters.length; i++) {
Array.prototype.push.apply(all, this.items[this.filters[i].value]);
}
}
return all
.filter(item => item.name.toLowerCase().indexOf(this.search.toLowerCase()) !== -1)
.filter(item => {
if (this.minLvl !== '' && this.maxLvl !== '') {
if (item.itemLevel >= this.minLvl && item.itemLevel <= this.maxLvl) return true;
} else if (this.minLvl == '' && this.maxLvl !== '') {
if (item.itemLevel <= this.maxLvl) return true;
} else if (this.minLvl !== '' && this.maxLvl == '') {
if (item.itemLevel >= this.minLvl) return true;
} else {
return true;
}
});
}
},
}
Here is I use one filter for min and max level. And when I will add more filter my code will be too big. Multiple filters can be active l at the same time.
How can I optimize my code?

how to change the loop to become a map?

I haven't found a way to change for into a map, so my plan won't use for but want to use maps in each function of this function
variantDefault = (colorId, sizeId) => {
let selected = [];
let i = 0;
if (this.props.index === 0) {
for (i = 0; i < this.props.values.length; i++) {
if (this.props.values[i].id === colorId) {
selected = this.props.values[i];
}
}
}
if (this.props.index === 1) {
for (i = 0; i < this.props.values.length; i++) {
if (this.props.values[i].id === sizeId) {
selected = this.props.values[i];
}
}
}
console.log(selected);
return selected;
};
you can try this way
variantDefault = (colorId, sizeId) => {
let selected = [];
if (this.props.index === 0) {
this.props.values.map((data) => {
if(data.id === colorId){
selected.push(data)
}
})
}
if (this.props.index === 1) {
this.props.values.map((data) => {
if (data.id === sizeId) {
selected.push(data)
}
})
}
console.log(selected);
return selected;
};
You could take Array#find and return the found item.
variantDefault = (colorId, sizeId) => this.props.values.find(
({ id }) => id === [colorId, sizeId][this.props.index]
) || [];
The use of Array.prototype.filter seems more fitting.
variantDefault = (colorId, sizeId) => {
if (this.props.index.isBetween(0, arguments.length, 1)) return [];
var compareTo = arguments[this.props.index];
return this.props.values.filter(item => item.id === compareTo);
};
If you only want to return the last element found (which is what you are doing in your example) then add an Array.prototype.pop call to the filtered array.
You can add the isBetween function by doing:
if (typeof Number.prototype.isBetween !== "function") {
Number.prototype.isBetween = function(start, end, inclusive) {
if (typeof start !== "number" || isNaN(start)) throw Error("Start is not a number");
if (typeof end !== "number" || isNaN(end)) throw Error("End is not a number");
return inclusive ? start <= this && this <= end : start < this && this < end;
};
}

creating a javascript recursive filter function

Is there any way of making this function recursive so that I do not need to create a switch for each length of filter criteria ?
var data = [
{a:'aaa',b:'bbb',c:'ccc',d:'ddd',e:'eee'},
{a:'aaa',b:'bbb',c:'ccc',d:'eee',e:'fff'},
{a:'xxx',b:'bbb',c:'ccc',d:'ddd',e:'fff'}
]
function select(data,where){
return data.filter(function(e){
var k = Object.keys(where);
switch(k.length){
case 1: return (e[k[0]] == where[k[0]]);
case 2: return (e[k[0]] == where[k[0]] && e[k[1]] == where[k[1]]);
case 3: return (e[k[0]] == where[k[0]] && e[k[1]] == where[k[1]] && e[k[2]] == where[k[2]]);
case 4: return (e[k[0]] == where[k[0]] && e[k[1]] == where[k[1]] && e[k[2]] == where[k[2]] && e[k[3]] == where[k[3]]);
case 5: return (e[k[0]] == where[k[0]] && e[k[1]] == where[k[1]] && e[k[2]] == where[k[2]] && e[k[3]] == where[k[3]] && e[k[4]] == where[k[4]]);
}
})
}
var where = {a:'aaa',b:'bbb'}
console.log(select(data,where));
It doesn't need to be recursive (I'm not sure you understand what that means), you just need to loop on the elements in where:
function select(data, where) {
return data.filter(function(e) {
var k = Object.keys(where);
return k.every(function(key) {
return e[key] == where[key];
});
})
}
var data = [
{a:'aaa',b:'bbb',c:'ccc',d:'ddd',e:'eee'},
{a:'aaa',b:'bbb',c:'ccc',d:'eee',e:'fff'},
{a:'xxx',b:'bbb',c:'ccc',d:'ddd',e:'fff'}
]
var where = {a:'aaa',b:'bbb'}
console.log(select(data,where));
Try this code:
function select(data, where) {
return data.filter(function (e) {
for (var key in where) {
if (where.hasOwnProperty(key)) {
if (e.hasOwnProperty(key)) {
if (e[key] != where[key]) {
return false;
}
}
else {
return false
}
}
}
return true;
})
}

Categories

Resources