I want to generate all possible pairs without repeated elements, so that each combination will be represented as the hashmap with each unique value for each key.
An idea is to transform the following inputs:
context: {
"environment": [
"dev",
"production",
"staging"
],
"filename": [
"info.txt",
"README.md"
],
"folder": "my_name"
}
variables: {"environment", "filename", "folder"}
Into unique combinations like this:
[
{"environment": "dev", "filename": "info.txt", "folder": "my_name"},
{"environment": "dev", "filename": "README", "folder": "my_name"},
{"environment": "staging", "filename": "info.txt", "folder": "my_name"}
...
]
So, I've tried to reach those ideas with the following piece of code:
use std::collections::{HashMap, BTreeSet};
use itertools::iproduct;
use serde_json::{json, Value as SerdeValue};
pub fn generate_subcontexts(
context: &Box<SerdeValue>,
variables: &BTreeSet<String>
) -> Vec<SerdeValue> {
let data: Vec<HashMap<String, SerdeValue>> = variables
.iter()
.filter(|variable_name| {
let value = match context.get(*variable_name) {
Some(value) => value,
None => return false,
};
match value {
SerdeValue::String(_) => true,
SerdeValue::Array(_) => true,
_ => false,
}
})
.map(|variable_name| {
let mut entry: HashMap<String, SerdeValue> = HashMap::new();
entry.insert(variable_name.clone(), context.get(variable_name).unwrap().clone());
entry
})
.collect();
iproduct!(data)
.map(|combination| json!(combination))
.collect()
}
However, instead of it, I'm getting only the serialized into JSON inputs (which are hashmaps). Anyone can guide me how to reorganize/fix the piece with iproduct!
macro, so I could get the desired result?