Set Functions

Sets in Flowata are collections of values where each value must be unique. This means that the same value cannot occur more than once in a set. Unlike arrays, sets are not ordered, so you cannot access or modify their elements using index-based accessors.

Creating a Set

You can create a new set using the set() function. By default, this function will return an empty set. However, if you want to initialize a set with some values, you can pass in an array of values.

setLocal(mySet, set()); // Creates an empty set
setLocal(fruitSet, set(["apple", "banana", "cherry"])); // Initializes a set with values

Adding Items

You can add an item to a set using the push(set, value) function. If the item already exists in the set, it won't be added again.

push(fruitSet, "date");
push(fruitSet, "apple"); // As "apple" already exists, it won't be added again

Removing Items

To remove an item from a set, you can use the removeItem(set, value) function.

removeItem(fruitSet, "banana");

Checking for Existence

To check if a set contains a specific item, you can use the has(set, value) function. This function returns true if the value exists in the set, otherwise false.

print(has(fruitSet, "apple")); // Output: true
print(has(fruitSet, "grape")); // Output: false

Size of the Set

To find out how many items are in a set, you can use the length(set) function.

print(length(fruitSet)); // e.g. Output: 3

Clearing a Set

To remove all items from a set, making it empty, you can use the clearSet(set) function.

clearSet(fruitSet);
print(length(fruitSet)); // Output: 0

Combining Sets

To combine two or more sets, you can use the union(...sets) function. This will return a new set that contains all unique values from the provided sets.

setLocal(vegSet, set(["carrot", "broccoli"]));
setLocal(combinedSet, union(fruitSet, vegSet));

clone(...sets)

When provided with a single set, it creates a shallow copy of the set. When provided with multiple sets, it combines them into a single set, ensuring all values are unique.

Examples:

  1. Cloning a Set

    setLocal(originalSet, set([1, 2, 3, 4]));
    setLocal(duplicateSet, clone(originalSet));
    
    // Adding a new value to the original set
    push(originalSet, 5);
    
    print(originalSet); // Output: {1, 2, 3, 4, 5}
    print(duplicateSet); // Output: {1, 2, 3, 4}
  2. Combining Multiple Sets

    setLocal(set1, set([1, 2]));
    setLocal(set2, set([3, 4, 2]));
    setLocal(result, clone(set1, set2));
    
    print(result); // Output: {1, 2, 3, 4}

Note: In the example above, even if set2 has a repeated value (2) that's also in set1, the resulting set result does not have any duplicates due to the nature of sets.