How to convert imperial to metric units? - javascript

This is more of a general question of both code and math. I'm not at all good at math, and I'm still learning how to apply math in programming.
Let's say, I have an object of data that has the amount, the measurement, and the type, such as feet or lb.
const data = {
0: {
'type': 'imperial',
'unit': 'ft',
'amount': 3
},
1: {
'type': 'imperial',
'unit': 'lb',
'amount': 5
},
2: {
'type': 'imperial',
'unit': 'mph',
'amount': 7
}
}
And I need to go through this data and convert each according to the type (assuming type is what it's called)
Object.keys(data).map(key => {
convert(data[key]['amount'], data[key]['type'], data[key]['unit'])
})
And the function converts this:
const convert = (amount, type, unit) => {
const calc = // ???
return calc;
}
My question is, how do I convert depending on the type of measurement? I know that 1 foot is 0.3048 meters, and if I needed to convert 5 feet to meters, I'd do 5*0.3048.
However, how can I apply this in code, with a list of imperial and metric units and how would I add this to the convert function?

You can have a converter Object with functions to convert and labels to display, here's an example ( adjust the values and units to your needs ) :
const data = {
0: {
type: "imperial",
unit: "ft",
amount: 3
},
1: {
type: "imperial",
unit: "lb",
amount: 5
},
2: {
type: "imperial",
unit: "mph",
amount: 7
}
};
const converter = {
imperialToMetric: {
ft: val => val * 0.3048,
lb: val => val * 0.453592,
mph: val => val * 1.60934,
labels: {
ft: "meters",
lb: "Kg",
mph: "kmh"
}
},
metric: {
// reverse the above
}
};
const result = Object.values(data).map(({ amount, type, unit }) => ({
amount: converter.imperialToMetric[unit](amount),
unit: converter.imperialToMetric.labels[unit],
type: "metric"
}));
console.log(result);

Related

can not use function to find sum of a part of an array (javascript)

I had 2 test cases like these (and maybe another one), some arrays like those one :
input: [{
name: 'Javascript',
coin: 1000
}, {
name: 'PHP',
coin: 1200
}, {
name: 'Dart',
coin: 1400
}, {
name: 'Ruby',
coin: 1600
}, {
name: 'ReactJS',
coin: 1600
}, {
name: 'React-Native',
coin: 1800
}, ]
or
intput: [{
name: 'Javascript',
coin: 1000
}, {
name: 'PHP',
coin: 1200
}, {
name: 'Dart',
coin: 1400
}]
I must write a javascript program to find a sum of the coin, for example, the 1st one is 8600
, the 2nd one is 3600.
I must use "reduce" function.
Here is mine
function run(courses) {
var i = 0;
var totalcoin = courses.reduce (function(total, course) {
i++;
return total + course.coin;
},0);
But it said to me that I had the error : Error: expected undefined to equal 8600.
Could you please give me some ideas for this problem ?
Thank you very much for your time.
Did you mean something like this?
your run function is incomplete, it should be returning the totalCoins value after reducing the array, and you need to run the function inorder to actually get the value
const array_first = [{ name: 'Javascript', coin: 1000 }, { name: 'PHP', coin: 1200 }, { name: 'Dart', coin: 1400 }, { name: 'Ruby', coin: 1600 }, { name: 'ReactJS', coin: 1600 }, { name: 'React-Native', coin: 1800 }]
const array_second = [{ name: 'Javascript', coin: 1000 }, { name: 'PHP', coin: 1200 }, { name: 'Dart', coin: 1400 } ];
const sum_first = run(array_first);
const sum_second = run(array_second);
console.log(`sum of coins in first array => ${sum_first}`);
console.log(`sum of coins in second array => ${sum_second}`);
function run(array) {
const sum = array.reduce((acc, curr) => acc + curr.coin, 0);
return sum;
}
Reference Material: Array.prototype.reduce()
The "reduce" function, like the other array functions, is itself a looping process -> so no need to have an iterator variable. So, something like
const sumOfCoins = courses.reduce((accumulator, course) => accumulator + course.coin, 0);
should give you the right answer. The reduce function goes through all elements of the array (course). The accumulator represents the current calculated value. So in your case, the accumulator gets "dragged along", each element is then added to the previous sum. The 0 at the end is the start value, so the accumulator will be 0 for the first operation. The return value of courses.reduce then is the last computed value.
A simple forEach loop can help you in this case:
So basically you have to loop through each element in the array and add/concatenate the value of coin in that element to a variable.
var input = [ { name: 'Javascript', coin: 1000 }, { name: 'PHP', coin: 1200 }, { name: 'Dart', coin: 1400 }, { name: 'Ruby', coin: 1600 }, { name: 'ReactJS', coin: 1600 }, { name: 'React-Native', coin: 1800 }, ]
function sumOfCoins(coinsArray){
let totalCoins = 0;
input.forEach((element)=>{
totalCoins += element.coin;
})
console.log(totalCoins); // 8600
}
sumOfCoins(input);
1) There is no need for the initialisation of i
var i = 0; // Not required
...
i++; // Not required
You can simply make it one-liner as:
const run = (courses) => courses.reduce((acc, { coin }) => acc + coin, 0);
const input = [{
name: "Javascript",
coin: 1000,
},
{
name: "PHP",
coin: 1200,
},
{
name: "Dart",
coin: 1400,
},
{
name: "Ruby",
coin: 1600,
},
{
name: "ReactJS",
coin: 1600,
},
{
name: "React-Native",
coin: 1800,
},
];
function run(courses) {
var totalcoin = courses.reduce(function(total, course) {
return total + course.coin;
}, 0);
console.log(totalcoin);
}
run(input);
If you want easier syntax you can use for..of loop as
function run(courses) {
let totalcoin = 0;
for (let obj of courses) {
totalcoin += obj.coin;
}
console.log(totalcoin);
}
which you can further simplify it using object destructuring as
function run(courses) {
let totalcoin = 0;
for (let { coin } of courses) {
totalcoin += coin;
}
console.log(totalcoin);
}

Reduce function wrapping data in an array

I have a reduce function that formats my data in the way i need but the only issue is the data is nested inside an array. I need to remove the outter array or just stop the reduce function from adding it in but every attempt Ive made to stop the reducer from wrapping the data in an array breaks my code. Ideally I would like my reducer to not wrap the data in an array but if thats not possible removing the array i need from inside the reducer cleanly seems like the only solution:
my data looks like this:
{
count: 4,
datapoints: [
{
Date: "2021-05-05",
score: 0,
},
{
Date: "2021-05-12",
score: 0,
},
{
Date: "2021-05-30",
score: 0,
},
{
Date: "2021-06-03",
score: 114,
},
],
};
my reducer function and api call:
const riskScores = await api.PCC.riskAssessment(userID, startdate, endDate);
const riskScoresFormatted = riskScores.datapoints.reduce((result, data) => {
const scores = result["riskAssessment"] || [];
scores.push({
value: data.score,
unit: "none",
recordedDate: data.Date,
method: "none",
type: "riskAssessment",
});
result["riskAssessment"] = scores;
return result;
}, []);
the output:
[riskAssessment: [{…}, {…}, {…}, {…}] ]
Ive tried just using the index of riskScoresFormatted[0] that comes back undefined. riskScoresFormatted.slice(1) just returns an empty array. Ive also tried targeting the first Item like riskScoresFormatted.riskAssessment this works but the value is sometimes null so it causes bugs later down the line.
Try changing the final reduce argument from [] to {} and I think you'll have better luck.
const riskScoresFormatted = riskScores.datapoints.reduce((result, data) => {
const scores = result["riskAssessment"] || [];
scores.push({
value: data.score,
unit: "none",
recordedDate: data.Date,
method: "none",
type: "riskAssessment",
});
result["riskAssessment"] = scores;
return result;
}, {});
Or, use Array.map() instead:
const riskScores = {
count: 4,
datapoints: [{
Date: "2021-05-05",
score: 0,
},
{
Date: "2021-05-12",
score: 0,
},
{
Date: "2021-05-30",
score: 0,
},
{
Date: "2021-06-03",
score: 114,
},
],
};
var riskScoresFormatted = riskScores.datapoints.map((data) => ({
value: data.score,
unit: "none",
recordedDate: data.Date,
method: "none",
type: "riskAssessment",
}));
console.log(riskScoresFormatted);

Apply Combo Discount to a Food Order

An app lets users order food from a menu. The menu has three types of selection: main, drink and dessert. A feature needs to be added which will discount the price by 10% for every main+drink combo (10% off every combo). All items ordered by the customer are stored in an array like so:
order = [
{id: 4, count: 1, type: "main", price: 10}
{id: 5, count: 2, type: "drink", price: 9.5}
]
As you can see, each item the customer orders has a count property. How can I apply the discount without mutating the order array or any of the object properties? Ideally I'd like to loop through the array, determine total number of combos (in the example above it would be 1), determine the total discount value and pass that value to another function which computes the order total. If anyone can suggest a better way of doing it, I'm all ears (or eyes in this case).
Also, what is the best way to express this problem from a technical point of view?
const userOrder = [
{ id: 4, count: 1, type: "main", price: 200 },
{ id: 5, count: 1, type: "drink", price: 100 }
];
const orderInfo = userOrder.reduce((acc, cur) => {
console.log('cur', cur)
if (acc[cur.type]) {
return {
...acc,
[cur.type]: cur.count,
totalAmount: (cur.count * acc.totalAmount)
}
} else {
return {
...acc,
[cur.type]: cur.count,
totalAmount: (cur.count * cur.price ) + acc.totalAmount
}
}
}, {
main: 0,
drink: 0,
totalAmount: 0
});
const noOfComobosPresent = Math.min(orderInfo.main, orderInfo.drink);
const totalDiscountValue = noOfComobosPresent * 10;
const finalAmount = orderInfo.totalAmount - ((orderInfo.totalAmount * totalDiscountValue ) / 100) ;
console.log('finalAmount', finalAmount)

How to calculate average values for documents with different type

I have a document like this
{
type: 'vehicles',
vin: 1234,
companyId: 123,
_id: 321
}
{
type: 'company',
name: 'x company',
_id: 123
}
{
type: 'company',
name: 'y company',
_id: 333
}
I am trying and to design map reduce function to get Average vehicle per company (allVehicle / allCompany), and i want to get the value by calling a key like this
key: ["averageVehiclesPerCompany"]
Below is perfect solution to calculate average
function calcAverage(companies) {
var totalVehicle = 0;
Object.keys(companies).map(function(key, index) {
var vehicle = 0;
if (!!companies[key].vin) {
vehicle = companies[key].vin;
}
totalVehicle += vehicle;
});
return parseFloat(totalVehicle / companies.length).toFixed(2);
}

array of object manipulation in javascript

I have an empty array inside the object like this,
const account = {
name: "David Reallycool",
expenses: []
}
and I need to create a function to add expense into an empty array, the result I need is,
const account = {
name: "David Reallycool",
expenses: [
{
descrition: "Rent",
amount: 1000
},
{
description: "Coffee",
amount: 2.50
}
]
How can I manipulate it?
const addExpense = (expense) => {
account.expenses.push(expense)
}
// use like this
addExpense({ description: 'Rent', amount: 1000 })
addExpense({ description: 'Coffee', amount: 2.5 })
const account = {
name: "David Reallycool",
expenses: []
}
function addExpense(description, amount){
account.expenses.push({"description": description, "amount":amount});
}
addExpense("Test", 500);
console.log(account);
You need to know two things for that:
Changing value in array reflects the change in the original array if you are passing the array as a function parameter as it is passed by reference.
You need to use push() function of Array prototype to add that object in your expenses array.
function addExpense(expensesArray, expense){
expensesArray.push(expense);
}
const account = {
name: "David Reallycool",
expenses: []
};
var expense = {
descrition: "Rent",
amount: 1000
}
addExpense(account.expenses, expense);
var expense = {
descrition: "Coffee",
amount: 2.5
}
addExpense(account.expenses, expense);
console.log(account);
As an object (account) is transferred not as a copy you can manipulate it without problems inside your function.
function addExpenses(inputAccount){
inputAccount.expenses = [
{
descrition: "Rent",
amount: 1000
},
{
description: "Coffee",
amount: 2.50
}
]
}
// will be called with
addExpenses(account);
// here account will have expenses content

Categories

Resources