getVector method
Generates a new Vector (Vector2, Vector3, Vector4) based on the mapping provided.
The mapping should be a List<String> consisting of the characters 'x', 'y', 'z', 'w'
representing the desired components for the new Vector. The mapping and the Vector must
have the same number of components.
For example, if the current Vector is a Vector3 with values [1, 2, 3] and the provided
mapping is ['x', 'x', 'y'], the resulting Vector will be a Vector3 with values [1, 1, 2].
If a 'z' or 'w' component is requested from a Vector2, or if a 'w' component is requested from a Vector3, the function will throw an Exception as these components do not exist in the respective Vectors.
Example:
var u = Vector.fromList([5,0,2,4]);
var v = u.getVector(['x','x','y']);
print(v); // "Vector3(5.0, 5.0, 0.0)"
u = Vector.fromList([5,0,2]);
v = u.getVector(['x','x','y','z']);
print(v); // "Vector4(5.0, 5.0, 0.0, 2.0)"
@param mapping A list of strings indicating the desired components for the new Vector. @throws Exception If the mapping requests a component that does not exist in the current Vector. @return A new Vector (Vector2, Vector3, Vector4) with components as specified by the mapping.
Implementation
Vector getVector(List<String> mapping) {
if (mapping.length < 2 || mapping.length > 4) {
throw Exception('Vector must have between 2 and 4 components');
}
// Create a dictionary that stores the maximum allowed index for each component
Map<String, int> maxAllowedIndex = {'x': 0, 'y': 1, 'z': 2, 'w': 3};
if (_data.length < 4) {
maxAllowedIndex['w'] = -1; // -1 indicates the component doesn't exist
}
if (_data.length < 3) {
maxAllowedIndex['z'] = -1;
}
List<dynamic> mappedComponents =
List.filled(mapping.length, Complex.zero());
for (int i = 0; i < mapping.length; i++) {
String component = mapping[i];
if (maxAllowedIndex[component] == -1) {
throw Exception('Invalid mapping for this Vector dimension');
}
mappedComponents[i] = _data[maxAllowedIndex[component]!];
}
// Then create the appropriate Vector.
if (mapping.length == 2) {
return Vector2(mappedComponents[0], mappedComponents[1]);
} else if (mapping.length == 3) {
return Vector3(
mappedComponents[0], mappedComponents[1], mappedComponents[2]);
} else {
return Vector4(mappedComponents[0], mappedComponents[1],
mappedComponents[2], mappedComponents[3]);
}
}