Issue
I have a map containing the sales for the last week. It is like this
Friday 0
Monday 0
Saturday 0
Sunday 0
Thursday 0
Tuesday 0
Wednesday 0
I want to sort it so from the current day it sorts the map backwards from the current day. So if the day is Thursday I want it to sort like this
Thursday 0
Friday 0
Saturday 0
Sunday 0
Monday 0
Tuesday 0
Wednesday 0
The key is a string and the value is a number in TypeScript. It also could be converted into an array of objects with the weekday and value.
Solution
You can create a mutable array of weekday names as a reference for the relative order:
type Weekday =
| "Monday"
| "Tuesday"
| "Wednesday"
| "Thursday"
| "Friday"
| "Saturday"
| "Sunday";
const weekdays: Weekday[] = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
];
Then you can use it to perform the sort operation on the map in another function.
Because Map instances can't actually be sorted (they "remember the original insertion order of the keys" 1) the sort operation involves copying the entries out of the map, clearing the map, then copying them back in — in the desired sort order.
In the function below, the index of the target weekday name is found in the array, then that element and all following elements are shifted to the beginning of the array so that it has the weekdays in the desired order. Then they're iterated over to sort the map in the same order:
function sortMap(map: Map<Weekday, number>, first: Weekday): void {
const index = weekdays.indexOf(first);
weekdays.unshift(...weekdays.splice(index, weekdays.length - index));
const cache = new Map(map.entries());
map.clear();
for (const weekday of weekdays) {
if (cache.has(weekday)) map.set(weekday, cache.get(weekday)!);
}
}
Here's the compiled JavaScript from the TS Playground in a runnable snippet so you can verify that it works according to the expectations in your question:
const weekdays = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
];
function sortMap(map, first) {
const index = weekdays.indexOf(first);
weekdays.unshift(...weekdays.splice(index, weekdays.length - index));
const cache = new Map(map.entries());
map.clear();
for (const weekday of weekdays) {
if (cache.has(weekday)) map.set(weekday, cache.get(weekday));
}
}
const map = new Map([
["Friday", 0],
["Monday", 0],
["Saturday", 0],
["Sunday", 0],
["Thursday", 0],
["Tuesday", 0],
["Wednesday", 0],
]);
sortMap(map, "Thursday");
console.log("Thursday:", [...map.entries()]);
sortMap(map, "Monday");
console.log("Monday:", [...map.entries()]);
// …etc.
Answered By - jsejcksn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.