can anyone explain to me why the following two arrow functions are equivalent? [duplicate] - ecmascript-6

This question already has answers here:
What do curly braces inside of function parameter lists do in es6?
(3 answers)
Closed 5 years ago.
I am pretty new to javascript. saw this on MDN regarding arrow functions.
Can anyone explain to me how does the 2nd one work? I understand the first one.
Not quite sure why we put length in an object, and then return the length???
Case 1 (which i understand from how it transformed from ES5):
materials.map((material) => {
return material.length;
}); // [8, 6, 7, 9]
Case 2 (not getting what {length} is doing here and also why do we return length:
materials.map(({length}) => length); // [8, 6, 7, 9]
Thank you so much!
Update:
So reading from the answer from Jeff B. It appears that the 2nd one is doing the following with destructuring:
materials.map(({length}) => length)
in which {length} will set a variable var length to equal to materials.length; and that's why we can simply return length. That makes sense. Thanks Jeff

This uses a destructuring assignment to get at the length property without saving the whole object. Specifically, this is a case of "object destructuring".
For instance:
let yourObject = {foo: 1, bar: 2}
let {bar} = yourObject;
// bar now equals 2
With this in mind, you can see how ({length}) => length sets the name length to the length property of the first parameter and then immediately returns it—making the two expressions equivalent.

Related

Use of function / return

I had the task to code the following:
Take a list of integers and returns the value of these numbers added up, but only if they are odd.
Example input: [1,5,3,2]
Output: 9
I did the code below and it worked perfectly.
numbers = [1,5,3,2]
print(numbers)
add_up_the_odds = []
for number in numbers:
if number % 2 == 1:
add_up_the_odds.append(number)
print(add_up_the_odds)
print(sum(add_up_the_odds))
Then I tried to re-code it using function definition / return:
def add_up_the_odds(numbers):
odds = []
for number in range(1,len(numbers)):
if number % 2 == 1:
odds.append(number)
return odds
numbers = [1,5,3,2]
print (sum(odds))
But I couldn’t make it working, anybody can help with that?
Note: I'm going to assume Python 3.x
It looks like you're defining your function, but never calling it.
When the interpreter finishes going through your function definition, the function is now there for you to use - but it never actually executes until you tell it to.
Between the last two lines in your code, you need to call add_up_the_odds() on your numbers array, and assign the result to the odds variable.
i.e. odds = add_up_the_odds(numbers)

Search Array of Strings with Non-sensitivity and Non-exact Match

Notice: I have made a few changes to the original question as my problem was not with commas within string.
I have a function I've been working on to exclude a cell value from a new array that contains a string I am searching for. I am doing this in order to put together a list for .setHiddenValues, since .setVisibleValues is not supported/implemented yet.
Here are my requirements for the sake of clarity:
Currently working:
Able to handle numbers as well as strings
Can search for lowercase and uppercase. visibleValueStr is user inputted so it can't be so sensitive.
colValueArr may have strings with commas within.
Still working on:
visibleValueStr can be a single value or array.
Case sensitivity("apple" to match "Apple")
Not exact matches("apple" to match "apple and banana")
Here is the function I currently have with the above met/unmet conditions:
function getHiddenValueArray(colValueArr,visibleValueArr){
var flatUniqArr = colValueArr.map(function(e){return e[0].toString();})
.filter(function(e,i,a){
return (a.indexOf(e.toString())==i && visibleValueArr.indexOf(e.toString()) == -1);
})
return flatUniqArr;
}
Please let me know what other info I need. I will update this question as I continue to do my research in the meanwhile.
Clarification from comments:
User inputs input(s) on HTML form and the variable is passed on as visibleValueArr.
When using Logger.log(visibleValueArr).
[apple, banana]
When using Logger.log(colValueArr).
[[Apple],[apple][apple][apple and banana],[apple],[banana, and apple],
[apple, and banana],[orange],[orange, and banana],[kiwi],[kiwi, and orange],
[strawberry]]
So when I use:
SpreadsheetApp.newFilterCriteria().setHiddenValues(newArray).build();
newArray should be the hidden values. In this case it should be:
orange
kiwi
kiwi, and orange
strawberry
Basically anything that does not contain what visibleValueArr is.
Instead, it returns all values back, hiding them all.
When I use [Apple, Banana] the "Apple" and "Banana" values are left out of newArray as they should be, but "Apple and Banana" and "Apple, and Banana" are not"
In addition, I would also like to understand what the e,i,a in function(e,i,a) represent. I'm trying to apply .toLowerCase() in different places to see if that resolves part of my issue but I'm not sure where to do it.
Issues:
Case sensitivity("apple" to match "Apple")
Not exact matches("apple" to match "apple and banana")
Solution:
Use regex-search with case insensitivity
Modified Script:
function getHiddenValueArray(colValueArr,visibleValueArr){
/*colValueArr = [["Apple"],["apple"],["orange"],["Apple, and Banana"]];
visibleValueArr = ['apple','banana'];*/
var flatUniqArr = colValueArr.map(function(e){return e[0].toString();})
.filter(function(e,i,a){
return (a.indexOf(e)==i && !(visibleValueArr.some(function(f){
return e.search(new RegExp(f,'i'))+1;
})));
});
//Logger.log(flatUniqArr); will log orange
return flatUniqArr;
}
References:
String#search
Array#some
Array#filter
Array#map

Accessing ImmutableJS OrderedSet()

Playing with ImmutableJS, documentation needs work and actual working examples.
const a = [["a"],["b"],["c"]]
const b = Immutable.List(a)
const c = Immutable.OrderedSet(a)
b.first() // => "a"
b.get(1) // => "b"
c.first() // => ["a"]
c.get(1) // => undefined !uh oh!
c.toList().get(1) // => "b" !indirect!
Question: How do I print out the 2nd element of .OrderedSet c without converting it to a .List or loop over the entire list?
You can do it such as:
// using some ES6 features
let ordSet = immutable.OrderedSet([1, 2, 3])
let iterator = ordSet[Symbol.iterator] // get iterator to the collection
iterator.next() // 1
iterator.next() // 2
iterator.next() // 3
This said, let me note that even if this is not the nicest syntax, from the point of performance, it is the best as it gets: OrderedSet does not provide random access to its elements, each element simply remembers its successor and predecessor. Therefore, getting n-th element requires n hops, whether immutable.js provides some fancy helper for it or not. AFAIK, such linked-list-like implementation of OrderedSet is inevitable, if add / delete should remain fast.

getting a random element from an array of movieclips(or labels in a timeline) in Flash CC . Actionscript 3

I am making a pretty neat quiz-game in flashCC right now and I definitely need your help.
My skills are more on the design then the programming side. So to many of you this might seem a baby question (and asked many times before) but from all the answers I saw so far, I couldn't get any results for my project.
So here is the thing :
I need the EXACT script for creating an array (with movieclips inside? or instance names of mcs? How does this even work?)
and a method, to pick a random element of this array without repeats until the "game is over".
Paul
The easiest way to pick a random element from an array without repeating is to first sort the array with a "random" function, then pop or shift items out of it until the array is empty.
Let's say you have an array of items which can be filled with either instances or instance names, you've chosen instance names: :
var FirstArray:Array = ["blau", "orange", "green"];
Now, you'll need a random sort function:
// you do not need to modify this function in any way.
// the Array.sort method accepts a function that takes in 2 objects and returns an int
// this function has been written to comply with that
function randomSort(a:Object, b:Object):int
{
return Math.random() > .5 ? -1 : 1;
}
The way a sort function normally works is it compares two objects and returns -1 if the first item precedes the second item, 1 if the opposite is true, and 0 if they are the same.
So what we're doing in the function above is returning -1 or 1 randomly. This should get the array all jumbled up when you call:
FirstArray.sort(randomSort);
Now that the array is randomly sorted, you can begin pulling items from it like so:
if(FirstArray.length) // make sure there's at least one item in there
{
// since you are using instance names, you'll need to use that to grab a reference to the actual instance:
var currentQuizItem:MovieClip = this[FirstArray.pop()];
// if you had filled your array with the actual instances instead, you would just be assigning FirstArray.pop() to currentQuizItem
// every time you call pop on an array, you're removing the last item
// this will ensure that you won't repeat any items
// do what you need to do with your MovieClip here
}
else
{
// if there aren't any items left, the game is over
}
When strung together, the above code should be enough to get you up and running.
You could try something like:
var array:Array = [1, 2, 3, 4, 5];
var shuffledArray:Array = [];
while (array.length > 0)
{
shuffledArray.push(array.splice(Math.round(Math.random() * (array.length - 1)), 1)[0]);
}
trace('shuffledArray: ', shuffledArray, '\nrandom item: ', shuffledArray[0]);

Difficulty splitting array and returning a value from within it; Javascript

I have got an array that consists of strings. I have made a function that searches the array based on the search term parameter. However, when i run the code it only ever outputs the string at index 0 of the array. I want it to return the corresponding url in the array when a search is run.
Any help would be very much appreciated. Thanks in advance.
So you are trying to return URL based on the String after the ~?
Do the line
arrayOfURL[i].toLowerCase().split('~')[i];
seem weird to you? Imagine as i increases, eg. i = 4
arrayOfURL[4].toLowerCase().split('~')[4];
Does that last [4] make sense?
I am guessing the reason it never got past the first element is because the code actually erroring out on that part.
I think what you want is (likewise for the return line, you'll want [0]
arrayOfURL[i].toLowerCase().split('~')[1];
I would also take a look at
if (z >= searchtoLower)
what are you trying to compare there?
The problem may be in the second i param:
var z = arrayOfURL[i].toLowerCase().split('~')[i];
The string will be splitted into 2 parts (index 0, 1). Why did you select part i?
This is a correct version of your program:
var arrayOfURL = [
"http://www.google.co.uk~Google is a search engine.",
"http://www.yahoo.co.uk~Yahoo is another search engine.",
"http://bing.com~Bing is a decision engine."
];
function findURL(arrayOfURL,search)
{
var searchtoLower = search.toLowerCase();
for (var i = 0; i < arrayOfURL.length; i++)
{
var z = arrayOfURL[i].toLowerCase().split('~')[1];
if (z.indexOf(searchtoLower) != -1)
return arrayOfURL[i];
}
return "Nothing Found!";
}
findURL(arrayOfURL,"decision")
I hope it can help you.
I think you should be doing
var terms = arrayOfURL[i].toLowerCase().split('~');
if(0 <= terms[1].indexOf(searchToLower))
// ^ ^
// | |-- 0 <= indexOf method determines
// | if searchToLower is a substring of terms[1]
// |
// |-- term[1] gets the part after the first "~"
and
return terms[0]; //terms[0] is the part before the first "~"
I would also consider returning null or the empty string "" in case of failure (instead of returning the arbritrary "Nothing Found!" message)