Protéger un état
rappels
let u ={a:1,b:1,c:1};
u = {...u, a:2, ["b"]:2, d:2}; // u = { a: 2, b: 2, c: 1, d: 2}
u = {a:2, ["b"]:2, d:2, ...u}; // u = { a: 1, b: 1, c: 1, d: 2}
let state = {
account: null
};
state.account="top"; //état non protégé
console.log(state)
// on protège l'état
function updateState(property, newData) {
state = Object.freeze({
...state,
[property]: newData
});
}
updateState("account",2);
console.log(state)
updateState("account",3);
console.log(state)
state.account="top"; // pluus possible
console.log(state)
L'affichage montre qu'une fois protégé on ne peut pas modifier l'état.
{ account: 'top' }
{ account: 2 }
{ account: 3 }
{ account: 3 }
Object.entries
const obj = { "un": 1, deux: 2, trois: 3 };
const tab = Object.entries(obj);
console.log(tab) //
- (3) [Array(2), Array(2), Array(2)]
- 0: (2) ['un', 1]
- 1: (2) ['deux', 2]
- 2: (2) ['trois', 3]
- length: 3
- [[Prototype]]: Array(0)
const obj2 = Object.fromEntries(
Object.entries(obj)
.map(([ key, val ]) => [ `${key}*2`, val * 2 ])
);
console.log(obj2);
- {un*2: 2, deux*2: 4, trois*2: 6}
- deux*2: 4
- trois*2: 6
- un*2: 2
https://codepen.io/dupontcodepen/pen/abEaYeQ
Reduce with Map : closest value
let value = 610;
const table = new Map([
[0,'yellowgreen'],
[150, 'green'],
[600, 'olive'],
[750, 'red'],
[800, 'black'],
]);
const closestKey = [...table.keys()].reduce( (acc, key) => {
return acc = ( Math.abs(acc-value) < Math.abs(key-value) ) ? acc : key
})
┌───────────────────┬─────┬───────────────┐
│ (iteration index) │ Key │ Values │
├───────────────────┼─────┼───────────────┤
│ 0 │ 0 │ 'yellowgreen' │
│ 1 │ 150 │ 'green' │
│ 2 │ 600 │ 'olive' │
│ 3 │ 750 │ 'red' │
│ 4 │ 800 │ 'black' │
└───────────────────┴─────┴───────────────┘
console.log(closestKey, table.get(closestKey))
// 600 olive
Map : en action
let value = 610;
const table = new Map([
[0,'yellowgreen'],
[150, 'green'],
[600, 'olive'],
[750, 'red'],
[800, 'black'],
]);
console.table(table.keys());
console.table([...table.keys()]);
table.keys() renvoie un itérateur !
[... table.keys()] renvoie un tableau !
Inscription à :
Articles (Atom)