The Tuple data structure represents an immutable collection of values. It is similar to an array but immutable, meaning its contents cannot be modified after creation. This implementation includes various methods to manipulate and work with tuples.
This module can be installed via npm:
npm install @terron/tuple
To create a new Tuple, simply instantiate the Tuple
class with the desired values:
const Tuple = require('@terron/tuple');
const tuple = new Tuple(1, 2, 3, 4, 5);
// or
const tuple = Tuple(1, 2, 3, 4, 5);
You can obtain the length of the Tuple using the length
property:
console.log(tuple.length); // Output: 5
Tuples can be iterated over using a for...of
loop or any other iterable method:
for (const value of tuple) {
console.log(value);
}
To convert a Tuple to a regular array, you can use the toArray
method:
console.log(tuple.toArray()); // Output: [1, 2, 3, 4, 5]
To convert a Tuple to a regular string, you can use the toString
method, String
class, +
operator:
console.log(tuple.toString()); // Output: (1, 2, 3, 4, 5)
console.log(String(tuple)); // Output: (1, 2, 3, 4, 5)
console.log(tuple + ` - my tuple`); // Output: (1, 2, 3, 4, 5) - my tuple
While Tuples are immutable, you can create modified copies using various methods:
To add values to a Tuple, use the set
method:
const newTuple = tuple.set(6, 7, 8);
console.log(newTuple.toString()); // Output: (1, 2, 3, 4, 5, 6, 7, 8)
To sort the values of a Tuple, use the sort
method:
const sortedTuple = tuple.sort((a, b) => a - b);
console.log(sortedTuple.toString()); // Output: (1, 2, 3, 4, 5)
To apply a function to each value of a Tuple, use the map
method:
const mappedTuple = tuple.map(value => value * 2);
console.log(mappedTuple.toString()); // Output: (2, 4, 6, 8, 10)
To reduce the values of a Tuple into a single value, use the reduce
method:
const sum = tuple.reduce((acc, value) => acc + value, 0);
console.log(sum); // Output: 15
To filter the values of a Tuple based on a predicate function, use the filter
method:
const filteredTuple = tuple.filter(value => value % 2 === 0);
console.log(filteredTuple.toString()); // Output: (2, 4)
To find the first element in a Tuple that satisfies a testing function, use the find
method:
const foundValue = tuple.find(value => value > 2);
console.log(foundValue); // Output: the first element in the Tuple that is greater than 2 (it's 3)
Also you can check if the provided data is a Tuple using the isTuple
method for main class:
console.log(
Tuple.isTuple(tuple),
Tuple.isTuple([1, 2, 3, 4, 5]),
Tuple.isTuple(Tuple)
)
/*
Output:
true
false
true
*/
If you want to support the author, i.e. me, then just install my package. Also, write all suggestions regarding future versions of the package in my DM Discord. ID: 1097169235295350936