I have created a function that receive some values from users an store them in a mapping. How to arrange the stored values in mapping according to a certain value ( Priority as in the shown example below)?
pragma solidity ^0.4.24;
contract Test {
// storage is packed based on how much data we actually want to store,
// to minimise the storage costs, we're going to use expected uint types
struct StudentType {
uint8 bonus; // 0 - 255
uint16 value1; // 0 - 65535
uint16 value2; // 0 - 65535
uint16 Priority; // 0 - 65535
}
mapping (address => StudentType) public studentsByAddress;
mapping (uint256 => address) public studentsByInsertId;
uint256 public studentCount = 0;
function saveNewRecord(address _address, uint8 _bonus, uint16 _value1, uint16 _value2) public {
// instance of struct student and map it to students mapping;
StudentType storage student = studentsByAddress[_address];
student.bonus = _bonus;
student.value1 = _value1;
student.value2 = _value2;
student.Priority = this.calculatePriority( _value1, _value2, _bonus);
// map address to current insert id
// ++uint makes our index start at 1 since the incrementation happens before
// if you want it to start at 0, then do uint++
studentsByInsertId[studentCount++] = _address;
}
/*
depending on the precision you actually want the more "zeroes" you're going to use.
*/
function calculatePriority(uint16 _value1, uint16 _value2, uint8 _bonus) pure public returns ( uint16 ) {
// store the calculation in a big enough value
uint256 result = ( ( ( 50 * _value1 ) + ( 50 * _value2 ) ) / _bonus ) / 100;
// convert result
return uint16( result );
}
/*
not really needed since you can use the "studentsByAddress" mapping method created by solidity
unless you want to "hide" or manipulate some data
*/
function get_ESU(address ins) view public returns (uint, uint, uint) {
return (
studentsByAddress[ins].value1,
studentsByAddress[ins].value2,
studentsByAddress[ins].Priority
);
}
}