Open8

JSchallenger にチャレンジ - Fundamentals / Sets

cyamycyamy

Check if value is present in Set

Write a function that takes a Set and a value as arguments
Check if the value is present in the Set

回答

function myFunction(set, val) {
  return set.has(val);
}
cyamycyamy

Convert a Set to Array

Write a function that takes a Set as argument
Convert the Set to an Array
Return the Array

回答

function myFunction(set) {
  return Array.from(set)
}
cyamycyamy

Get union of two sets

Write a function that takes two Sets as arguments
Create the union of the two sets
Return the result
Tipp: try not to switch to Arrays, this would slow down your code

回答

function myFunction(a, b) {
  return new Set([...a, ...b])
}
cyamycyamy

Creating Javascript Sets

Write a function that takes three elements of any type as arguments
Create a Set from those elements
Return the result

回答

function myFunction(a, b, c) {
  return new Set([a,b,c])
}
cyamycyamy

Delete element from Set

Write a function that takes a Set and a value as argument
If existing in the Set, remove the value from the Set
Return the result

回答

function myFunction(set, val) {
  set.delete(val)
  return set
}
cyamycyamy

Add multiple elements to Set

Write a function that takes a Set and an array as arguments
If not already existing, add each element in the array to the Set
Return the modified Set

回答

function myFunction(set, arr) {
  return new Set([...set, ...arr]);
}
cyamycyamy

Get Intersection of two Javascript Sets

Write a function that takes two sets (a and b) as arguments
Get the intersection of the sets
In other words, return a set containing all elements that are both in a as well as b

回答

function myFunction(a, b) {
  return new Set([...a].filter(i => b.has(i)));
}