Combine multiple if statements with multiple properties - javascript

I'm looking into using my loop to combine and narrow down this piece of code into maybe a switch statement or other methods, how would I be able to achieve that? This is what I have so far which has worked for me but I also have other items[i].ApplicationType such as 'OneDrive', 'Teams', etc..
for(i = 0; i < items.length; i++)
{
if(items[i].ComputerType == 'Windows' && items[i].RequestType == 'Single User' && items[i].ApplicationType == 'OneDrive')
{
ODwindows += 1;
}
else if(items[i].ComputerType == 'Windows' && items[i].RequestType == 'Single User' && items[i].ApplicationType == 'Teams')
{
Teamswindows += 1;
}
else if(items[i].ComputerType == 'Mac' && items[i].RequestType == 'Single User' && items[i].ApplicationType == 'OneDrive')
{
ODmac += 1;
}
else if(items[i].ComputerType == 'Mac' && items[i].RequestType == 'Single User' && items[i].ApplicationType == 'Teams')
{
Teamsmac += 1;
}
else if(items[i].ComputerType == 'Both' && items[i].RequestType == 'Team' && items[i].ApplicationType == 'OneDrive')
{
ODboth += 1;
}
else if(items[i].ComputerType == 'Both' && items[i].RequestType == 'Team' && items[i].ApplicationType == 'Teams')
{
Teamsboth += 1;
}
}

You could take an object with the different types and count by nested properties.
var count = {
'Single User': {
Windows: {
OneDrive: 0,
Teams: 0
},
Mac: {
OneDrive: 0,
Teams: 0
}
},
Team: {
Both: {
OneDrive: 0,
Teams: 0
}
}
};
for (let { RequestType, ComputerType, ApplicationType } of items) {
count[RequestType][ComputerType][ApplicationType]++;
}

You could create a key for each unique combination of ComputerType, RequestType and ApplicationType separated by _. Then use destructuring to get each count to variables:
const output = {};
items.forEach(o => {
const key = [o.ComputerType, o.RequestType, o.ApplicationType].join('_')
output[key] = output[key] + 1 || 1
})
const {
['Windows_Single User_OneDrive']: ODwindows,
['Windows_Single User_Teams']: Teamswindows,
['Mac_Single User_OneDrive']: ODmac,
['Mac_Single User_Teams']: Teamsmac,
['Both_Team_Teams']: ODboth,
['Both_Team_Teams']: Teamsboth
} = output;

const items = [{ComputerType: "Windows", RequestType:"Single", ApplicationType: "OneDrive"}]
const countObj = items.reduce((accum, item) => {
const { ComputerType, RequestType, ApplicationType } = item
const key = `${ComputerType}_${RequestType}_${ApplicationType}`
return {
...accum,
[key]: accum[key] ? accum[key] + 1 : 1
}
}, {})
console.log(countObj)

Related

How can you filter out related words in large list quickly

I am running this code on ~479k words and it is taking a very long time:
const fs = require('fs')
const words = fs.readFileSync('dicts/eng.csv', 'utf-8')
.split(/\n/)
.filter(x => x && !x.match('-') && !x.match(/[A-Z]/))
.reduce((m, x) => {
m[x] = true
return m
}, {})
for (let word in words) {
for (let form in words) {
if (form.indexOf(word) == 0) {
if (form.length == word.length + 2 && form.endsWith('ed')) {
delete words[form]
} else if (form.length == word.length + 4 && form.endsWith('tion')) {
delete words[form]
} else if (form.length == word.length + 3 && form.endsWith('ing')) {
delete words[form]
} else if (form.length == word.length + 2 && form.endsWith('er')) {
delete words[form]
} else if (form.length == word.length + 2 && form.endsWith('or')) {
delete words[form]
} else if (form.length == word.length + 3 && form.endsWith('est')) {
delete words[form]
} else if (form.length == word.length + 1 && form.endsWith('s')) {
delete words[form]
} else if (form.length == word.length + 3 && form.endsWith('ers')) {
delete words[form]
} else if (form.length == word.length + 4 && form.endsWith('ings')) {
delete words[form]
}
}
}
}
fs.writeFileSync('dicts/eng.out.csv', Object.keys(words).sort().join('\n'))
How can I speed this up to take only a fraction of the time, on the order of a second or two or whatever is more realistic?
Is there some data structure I need to convert this list into that is better suited to a faster algorithm?
this may work:
const fs = require('fs')
let words = fs.readFileSync('dicts/eng.csv', 'utf-8')
.split(/\n/)
.filter(x => x && !x.match('-') && !x.match(/[A-Z]/)).sort()
let out = new Set, root = words[0];
for (let word of words) {
if (!word.startsWith(root))
root = word;
word = root === word ? root : word
.replace(/(ed|tion|ing|er|or|est|s|ers|ings)$/, '')
out.add(word);
}
fs.writeFileSync('dicts/eng.out.csv', [...out].join('\n'));

Javascript filter between two string dates in Vue component

I'm working with Vue in a Laravel app. Everything below works except the last one. I can't seem to find the right search terms to fit this situation. Sorry if it's a duplicate.
Here is my current code:
return [...this.tableData].filter((salesorders) => {
if (this.selectOption == '6') {
return salesorders.order_status.match(this.status);
}
if (this.selectOption == '1') {
return salesorders.number.includes(this.searchInput);
}
if (this.selectOption == '2' && this.choice == 'is') {
var ship_date = moment(String(this.first_date)).format('MM-DD-YYYY');
return salesorders.requested_ship_date.match(ship_date);
}
if (this.selectOption == '2' && this.choice == 'is not') {
var ship_date = moment(String(this.first_date)).format('MM-DD-YYYY');
return !salesorders.requested_ship_date.match(ship_date);
}
if (this.selectOption == '2' && this.choice == 'is between') {
var ship_date1 = moment(String(this.first_date)).format('MM-DD-YYYY');
var ship_date2 = moment(String(this.end_date)).format('MM-DD-YYYY');
return salesorders.requested_ship_date >= ship_date1 && salesorders.requested_ship_date >= ship_date2;
}
});
I just figured it out:
return salesorders.requested_ship_date >= ship_date1 && salesorders.requested_ship_date <= ship_date2;

Is there a better way to change button display in javascript/Vue?

After writing so many if else, I feel very tired. I'm using Vue. The following code are written in the script section of the vue file. I get a json from file, and then read the values in json, then set what button should be display based on employee level and on application status. Is there a better way to change the button display status in Vue?
if (
(this.GLOBAL2.jsonForGlobal.employeeLevel == "1" &&
(this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Checking" ||
this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending" ||
this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Approved")) ||
(this.GLOBAL2.jsonForGlobal.employeeLevel == "2" &&
(this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending" ||
this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Approved")) ||
(this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Approved")
) {
this.pullDisplay = true;
} else {
this.pullDisplay = false;
};
if (
this.GLOBAL2.jsonForGlobal.employeeLevel == "1" &&
this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Revising"
) {
this.cancelDisplay = true;
} else {
this.cancelDisplay = false;
};
if (
(this.GLOBAL2.jsonForGlobal.employeeLevel == "1" &&
this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Revising") ||
(this.GLOBAL2.jsonForGlobal.employeeLevel == "2" &&
this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Checking") ||
(this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending")
) {
this.saveDisplay = true;
} else {
this.saveDisplay = false;
};
if (
this.GLOBAL2.jsonForGlobal.employeeLevel == "1" &&
this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Revising"
) {
this.reviseDisplay = true;
} else {
this.reviseDisplay = false;
};
if (
(this.GLOBAL2.jsonForGlobal.employeeLevel == "2" &&
this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Checking") ||
(this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending")
) {
this.sendDisplay = true;
} else {
this.sendDisplay = false;
};
if (
(this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending") ||
(this.GLOBAL2.jsonForGlobal.employeeLevel == "2" &&
this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Checking")
) {
this.approvalDisplay = true;
} else {
this.approvalDisplay = false;
};
And also there are a few ones need three conditions:
if (
this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
this.GLOBAL2.jsonForGlobal.detail[this.detailId].requestCategory ==
"External Request" &&
this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus ==
"Pending"
) {
this.returnDisplay = true;
} else {
this.returnDisplay = false;
}
Going with a configuration based approach will make your code much more easy to edit and to read.
const levels = {
'1': {
pullDisplayStatus: ['Checking', 'Pending', 'Approved'],
cancelDisplayStatus: ['Revising'],
saveDisplayStatus: ['Revising'],
reviseDisplayStatus: ['Revising'],
sendDisplayStatus: [],
approvalDisplayStatus: [],
},
'2': {
pullDisplayStatus: ['Pending', 'Approved'],
cancelDisplayStatus: [],
saveDisplayStatus: ['Checking'],
reviseDisplayStatus: [],
sendDisplayStatus: ['Checking'],
approvalDisplayStatus: ['Checking'],
},
'3': {
pullDisplayStatus: ['Approved'],
cancelDisplayStatus: [],
saveDisplayStatus: ['Pending'],
reviseDisplayStatus: [],
sendDisplayStatus: ['Pending'],
approvalDisplayStatus: ['Pending'],
},
}
const jsonForGlobal = this.GLOBAL2.jsonForGlobal;
const currentStatus = jsonForGlobal.detail[this.detailId].currentStatus;
const level = levels[jsonForGlobal.employeeLevel];
this.pullDisplay = level.pullDisplayStatus.indexOf(currentStatus) > -1;
this.cancelDisplay = level.cancelDisplayStatus.indexOf(currentStatus) > -1;
this.saveDisplay = level.cancelDisplayStatus.indexOf(currentStatus) > -1;
this.reviseDisplay = level.reviseDisplayStatus.indexOf(currentStatus) > -1;
this.sendDisplay = level.reviseDisplayStatus.indexOf(currentStatus) > -1;
If you use a property often it makes sense to introduce a local variable for it to clean things up:
const { employeeLevel, detail: { [this.detailId]: { currentStatus }}} = his.GLOBAL2.jsonForGlobal;
Secondly you don't need the if / else, you can just assign the boolean:
this.pullDisplay = (
employeeLevel == "1" && ["Checking", "Pending", "Approved"].includes(currentStatus) ||
employeeLevel == "2" && ["Pending", "Approved"].includes(currentStatus) ||
employeeLevel == "3" && currentStatus == "Approved"
)

Divide two Inputs and multiply 100

I have the two functions match and and total working properly. I want the function total project match to divide the first function over the second function multiply times 100. the last function isn't working!
Here is my code so far :
matchContribution.subscribe(function (newValue) {
if (newValue != undefined && newValue != '') {
matchContribution(formatInt(newValue));
var dataValue = Number(matchContribution().replace(/\,/g, ''));
if (dataValue > 999999999999.99 || dataValue < 0) {
matchContribution('');
}
if (loading == false) {
sendCommand('SAVE');
}
}
});
var totalProjectCost = ko.computed(function () {
var total = 0;
var hasUserInput = false;
if (grantRequest() != '' && grantRequest() != undefined) {
hasUserInput = true;
total = total + Number(String(grantRequest()).replace(/\,/g, ''));
}
if (matchContribution() != '' && matchContribution() != undefined) {
hasUserInput = true;
total = total + Number(String(matchContribution()).replace(/\,/g, ''));
}
if (total == 0) {
if (!hasUserInput)
return '';
else
return formatInt('0');
}
else {
if (loading == false) {
sendCommand('SAVE');
}
return formatInt(total);
}
});
var totalProjectMatch = matchContribution()/totalProjectCost();
if(totalProjectMatch>=0)
totalProjectMatch = Math.floor(totalProjectMatch);
else
totalProjectMatch = Math.ceil(totalProjectMatch);
var totalProjectMatch = ko.computed(function () {
var total = 0;
var hasUserInput = false;
if ((grantRequest() != '' && grantRequest() != undefined) && (matchContribution() != '' && matchContribution() != undefined) && (totalProjectCost() != '' && totalProjectCost() != undefined)) {
hasUserInput = true;
total = Number(String(matchContribution()).replace(/\,/g, '')) / Number(String(totalProjectCost()).replace(/\,/g, ''));
total = total * 100;
}
if (total == 0) {
if (!hasUserInput)
return '';
else
return formatInt('0');
}
else {
if (loading == false) {
sendCommand('SAVE');
}
return formatNumber(total);
}
});
I solved the problem! Thanks a lot! Hope that helps other people.

Using for loop to order dependency

var input = [ "KittenService: ", "Leetmeme: Cyberportal", "Cyberportal: Ice", "CamelCaser: KittenService", "Fraudstream: Leetmeme", "Ice: "];
var output = [];
function valid(input) {
for(var i = 0; i < input.length; i++) {
var array = input[i].trim().split(':');
var packageName = array[0].trim();
var dependencyName = array[1].trim();
if(array.length > 1 && dependencyName === '') {
if(output.indexOf(packageName) === -1) {
output.push(packageName);
}
else {
return;
}
}
else if(array.length > 1 && dependencyName !== '') {
if (output.indexOf(dependencyName) === -1) {
output.push(dependencyName);
if(output.indexOf(dependencyName) > -1) {
if(output.indexOf(packageName) > -1) {
continue;
}
else {
output.push(packageName);
}
}
}
else if(output.indexOf(dependencyName) > -1) {
output.push(packageName);
}
}
}
return output.join(', ');
}
valid(input);
I am trying to figure out way to make the output to become
"KittenService, Ice, Cyberportal, Leetmeme, CamelCaser, Fraudstream"
Right it logs
'KittenService, Cyberportal, Leetmeme, Ice, CamelCaser, Fraudstream'
I am not sure how to make all the input with dependencies to pushed before input with dependencies.
Problem was just that you were returning if no package name instead of using a continue.
var input =[ "KittenService: CamelCaser", "CamelCaser: " ]
var output = [];
function valid(input) {
for(var i = 0; i < input.length; i++) {
var array = input[i].trim().split(':');
var packageName = array[0].trim();
var dependencyName = array[1].trim();
if(array.length > 1 && dependencyName === '') {
if(output.indexOf(packageName) === -1) {
output.push(packageName);
}
else {
continue;
}
}
else if(array.length > 1 && dependencyName !== '') {
if (output.indexOf(dependencyName) === -1) {
output.push(dependencyName);
if(output.indexOf(dependencyName) > -1) {
output.push(packageName);
}
}
}
}
return output;
}
console.log(valid(input));

Categories