Skip to content

Commit b49d747

Browse files
committed
Implement cardinality function for array
1 parent 6b73cd9 commit b49d747

2 files changed

Lines changed: 27 additions & 1 deletion

File tree

crates/gitql-std/src/array/mod.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ pub fn register_std_array_functions(map: &mut HashMap<&'static str, StandardFunc
3333
map.insert("array_dims", array_dims);
3434
map.insert("array_replace", array_replace);
3535
map.insert("trim_array", array_trim);
36+
map.insert("cardinality", array_cardinality);
3637
}
3738

3839
#[inline(always)]
@@ -159,6 +160,13 @@ pub fn register_std_array_function_signatures(map: &mut HashMap<&'static str, Si
159160
}),
160161
},
161162
);
163+
map.insert(
164+
"cardinality",
165+
Signature {
166+
parameters: vec![Box::new(ArrayType::new(Box::new(AnyType)))],
167+
return_type: Box::new(IntType),
168+
},
169+
);
162170
}
163171

164172
pub fn array_append(inputs: &[Box<dyn Value>]) -> Box<dyn Value> {
@@ -267,3 +275,20 @@ pub fn array_trim(inputs: &[Box<dyn Value>]) -> Box<dyn Value> {
267275
array.truncate(array_len - n as usize);
268276
Box::new(ArrayValue::new(array, array_type))
269277
}
278+
279+
#[allow(clippy::borrowed_box)]
280+
pub fn array_cardinality(inputs: &[Box<dyn Value>]) -> Box<dyn Value> {
281+
fn calculate_array_cardinality(value: &Box<dyn Value>) -> usize {
282+
if let Some(array) = value.as_array() {
283+
if array.is_empty() {
284+
return 0;
285+
}
286+
287+
return array.len() * calculate_array_cardinality(&array[0]);
288+
}
289+
1
290+
}
291+
292+
let cardinality: usize = calculate_array_cardinality(&inputs[0]);
293+
Box::new(IntValue::new(cardinality as i64))
294+
}

docs/functions/array.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,5 @@
2020
| ARRAY_POSITIONS | Array, Any | Array<Integer> | Return the an array of positions of element in array. |
2121
| ARRAY_DIMS | Array | Text | Returns a text representation of the array's dimensions. |
2222
| ARRAY_REPLACE | Array, Any, Any | Array | Replaces each array element equal to the second argument with the third argument. |
23-
| TRIM_ARRAY | Array, Integer | Array | Remove the last n elements from the array. |
23+
| TRIM_ARRAY | Array, Integer | Array | Remove the last n elements from the array. |
24+
| CARDINALITY | Array | Integer | Counts the total number of array elements. |

0 commit comments

Comments
 (0)