Skip to content

Commit e94f043

Browse files
committed
map function makes a map with good time complexity
1 parent dac030d commit e94f043

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

src/algorithm/map.rs

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,21 @@ impl Value {
2222
values.row_count()
2323
)));
2424
}
25-
Ok(Array::new(2, [Boxed(self), Boxed(values)]).into())
25+
let capacity =
26+
((self.row_count() as f64 / LOAD_FACTOR).ceil() as usize).next_power_of_two();
27+
let item = Boxed(
28+
Array::new(
29+
capacity,
30+
repeat(EMPTY_NAN).take(capacity).collect::<EcoVec<_>>(),
31+
)
32+
.into(),
33+
);
34+
let mut map = Value::Box(Array::new(2, [item.clone(), item]));
35+
map.meta_mut().map_len = Some(0);
36+
for (key, value) in self.into_rows().zip(values.into_rows()) {
37+
map.insert(key, value, env)?;
38+
}
39+
Ok(map)
2640
}
2741
/// Turn a map array into its keys and values
2842
pub fn unmap(mut self, env: &Uiua) -> UiuaResult<(Value, Value)> {
@@ -372,7 +386,7 @@ impl<'a> PairMut<'a> {
372386
len
373387
}
374388
fn grow(&mut self) {
375-
if self.capacity() == 0 || self.len() as f64 / self.capacity() as f64 > LOAD_FACTOR {
389+
if self.capacity() == 0 || (self.len() as f64 / self.capacity() as f64) > LOAD_FACTOR {
376390
fn grow_impl<K, V>(keys: &mut Array<K>, values: &mut Array<V>, new_capacity: usize)
377391
where
378392
K: MapItem + ArrayValue,

0 commit comments

Comments
 (0)