JS How to set values outside scope with single line [duplicate] - javascript

This question already has answers here:
Object destructuring without var, let or const
(4 answers)
Is it possible to destructure onto an existing object? (Javascript ES6)
(16 answers)
Closed 3 years ago.
if the function calculateAvgGainLoss response includes avgGain, avgLoss we can get these values like this.
const { avgGain, avgLoss } = calculateAvgGainLoss(prices);
I want to set these values to the variable that defined outside of the function. How can I do that ? Example below.
describe("test", () => {
let avgGain: number, avgLoss: number;
it("Calculate average gain & loss", () => {
const prices = [...];
/*...This isn't working, has to be changed...*/ { avgGain, avgLoss } = calculateAvgGainLoss(prices);
expect(avgGain).toBe(0.24);
expect(avgLoss).toBe(0.1);
});
});

Beginning the line by a { confuses parsers (is it the beginning of a scope? an object? etc). Just bypass this by wrapping your line with parenthesis:
describe("test", () => {
let avgGain: number, avgLoss: number;
it("Calculate average gain & loss", () => {
const prices = [...];
({ avgGain, avgLoss } = calculateAvgGainLoss(prices)); // <--
expect(avgGain).toBe(0.24);
expect(avgLoss).toBe(0.1);
});
});

Related

Odd syntax for setting an object's property in JavaScript [duplicate]

This question already has answers here:
What does this symbol mean in JavaScript?
(1 answer)
What do square brackets around a property name in an object literal mean?
(2 answers)
Closed 3 months ago.
What is happening in the code on line 10 ({[last]: newObj}) in the following snippet:
How is JS able to use the value of parameter last instead of using last as the property name?
let first = 'first';
let last = 'last';
function foo(first, last) {
let newObj = {
name: 'newObj'
};
let obj = {};
Object.assign(obj, {[last]: newObj});
return obj;
}
console.log(foo('bye', 'hey')); // { hey: { name: 'newObj' } }
Thanks.

Functions returning an object with the same attributes doesn't work [duplicate]

This question already has answers here:
Object destructuring without var, let or const
(4 answers)
Closed 1 year ago.
So my problem is the following:
I have the two functions
getDatesAndStringOfTimespan(timeSpan, goBack) returns {from, to}
limitFromAndTo(from, to, fromLimit, toLimit) returns {from, to}
I now want to do the following:
let { from, to } = getDatesAndStringOfTimespan(timeSpan, goBack)
{ from, to } = limitFromAndTo(from, to, fromLimit, toLimit)
But it says 'Declaration or statement expected.' I know I could do
let { from, to } = getDatesAndStringOfTimespan(timeSpan, goBack)
let object = limitFromAndTo(from, to, fromLimit, toLimit)
from = object.from
to = object.to
It just seems like there is a smarter way of doing this.
I can see two other ways of doing this.
Wrap the second assignment in parentheses to help the js compiler to understand what's happening (I'm not recommending this, just making your implementation possible in practice)
let { from, to } = getDatesAndStringOfTimespan(timeSpan, goBack);
({ from, to } = limitFromAndTo(from, to, fromLimit, toLimit))
Only destructure the second values
const dates = getDatesAndStringOfTimespan(timeSpan, goBack)
const { from, to } = limitFromAndTo(dates.from, dates.to, fromLimit, toLimit)
I would prefer #2 in a code review, as it's clearer to see what's going on - no magic brackets, and more readable

Please help to understand what are a curly braces here for -> { signal }? [duplicate]

This question already has answers here:
Javascript object literal: what exactly is {a, b, c}?
(3 answers)
Closed 1 year ago.
What means curly braces around signal?
const controller = new AbortController();
const signal = controller.signal;
readFile(fileInfo[0].name, **{ signal }**, (err, buf) => {
...
Thanks.
If you read the documentation you'll note that the second argument to readfile is options which is an object, one property of which is signal.
In ES6/ES2015 It's an object property value shorthand:
if you have a variable named signal
const signal = "test"
const ob = {signal};
console.log(ob.signal); // "test"
is equal to ES5's
const signal = "test"
const ob = {signal: signal};
console.log(ob.signal); // "test"

Typescript arrow function parantheses in filter method [duplicate]

This question already has answers here:
When should I use a return statement in ES6 arrow functions
(6 answers)
Arrow function without curly braces
(9 answers)
Closed 2 years ago.
Imagine I have an array containing movie objects such that
const movies: Movie[] = [ movie1, movie2, movie3, movie4 ];
I want to select a movie, for instance I have chosen movie2, then I want movie2 to be removed.
The following code works, Imagine m is the selected movie:
movies = movies.filter( m => m !== movie );
I want to understand how the arrow function works and tried the following code but it did not work.
movies = movies.filter( m => {
m !== movie;
});
What is the difference between those two codes?
The difference is, that the short-hand version implicitly returns the result. The long version from you is missing the return statements, like:
movies = movies.filter( m => {
return m !== movie;
});

Getting random element from constants that they have subs [duplicate]

This question already has answers here:
Pick random property from a Javascript object
(9 answers)
Closed 2 years ago.
const example1 = {
subex1: {
...something...
},
subex2: {
...something...
}
};
This is the code. For some reason, I can't use example1[Math.floor(Math.random() * example1.length)] code. How can I get a random item from sub constants (actually idk their name if they're not subconst).
You can do something like this.
const example1 = {
subex1: {
"hello": "hello"
},
subex2: {
"Hello1": "hello1"
}
};
console.log(Object.keys(example1)[Math.floor(Math.random()*Object.keys(example1).length)]);

Categories

Resources