Rarity Datapack

I want to add a rarity system to my datapack. Until now it was only possible to get the different raritys of items through reforging with a smithingtable. Is there any way to make it automatically so when you craft like a diamond sword the crafted sword gets a random rarity? My problem with this system was that when you have a second diamond sword in your inventory that one gets deleted and replaced not that you just crafted.
Continue to help post