In this scenario, we have an 'api_fetchData' function that retrieves data from the server. Depending on the route, the data can be in the form of a table or a tree structure. There are two states that need to be updated based on the received data. Additionally, if the data is in table format, the records should be sorted by priority. I am exploring how to achieve this using functional programming techniques, perhaps using Ramda or other similar libraries.
const tree=null;
and
const table = null:
//table
{
type: "table",
records: [
{
id: 1,
priority: 15
},
{
id: 2,
priority: 3
}
]
}
//tree
{
type: "tree",
children: [
{
type: "table",
records: [
{
id: 1,
priority: 15
},
{
id: 2,
priority: 3
}
]
}
]
}
This is the approach I took:
//define utils
const Right = x => ({
map: f => Right(f(x)),
fold: (f, g) => g(x),
inspect: x => `Right(${x})`
});
const Left = x => ({
map: f => Left(x),
fold: (f, g) => f(x),
inspect: x => `Left(${x})`
});
const fromNullable = x => (x != null ? Right(x) : Left(null));
const state = reactive({
path: context.root.$route.path,
tree: null,
table: null
});
// final code:
const fetchData = () => {
return fromNullable(mocked_firewall[state.path])
.map(data =>
data.type === "tree"
? (state.tree = data)
: (state.table = R.mergeRight(data, {
records: prioritySort(data.records)
}))
)
.fold(
() => console.log("there is no data based on selected route"),
x => console.log(x)
);
};