The Atomics static method sub() used to perform subtraction operation with a given value at a given position in the array. It returns the old value at that position. It guarantees that no other write happens until the modified value is written on shared object.
1 Atomics.sub(<typedArray>, <index>, <value>)
typeArray : A typed array object to subtract specified value, It can be of type Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, or BigUint64Array.
index : An index value which specify the position
value : A value to subtract from the specified index position
1 const shared= new SharedArrayBuffer(1024);
2 const ua = new Uint8Array(shared);
3
4 ua[0] = 100;
5
6 console.log("An initial value is :", ua[0]);
7
8 let res1 = Atomics.sub(ua, 0, 50);
9 console.log("A previous value is :", res1);
10
11
12 let res2 = Atomics.sub(ua, 0, 10);
13 console.log("A previous value is :", res2)
14
15 let res3 = Atomics.load(ua, 0);
16 console.log("A resulting value is :", res3);
In the above example, A Uint8Array is created by specifying shared buffer array object. A new value assign at position 0. A sub() method called by specifying index 0 and 50 which subtracted and returns old value 100. Again, a sub() method called by specifying index 0 and 10 which subtract and old value 50 returns. A load() method called which returns index 0 value and prints 40 on console.
1 An initial value is : 100
2 A previous value is : 100
3 A previous value is : 50
4 A resulting value is : 40
Subtract value dynamically
Subtract value dynamically
1 let values = [3, 5, 8, 9, 5];
2
3 const shared= new SharedArrayBuffer(1024);
4 const ua = new Int8Array(shared);
5 ua[0] = 60;
6
7 console.log("Initial value :", ua[0]);
8 values.forEach(val => {
9 let x = Atomics.sub(ua, 0, val);
10 console.log("A previous value is :", x);
11 });
12 let res = Atomics.load(ua, 0);
13 console.log("Result after subtraction :", res);
In the above example, an array is declared and initialized with values. An array elements are iterating using forEach() method by specifying a callback function. A callback function subtract element value by calling an Atomics sub() method and returns a previous value and print. A initial and resulting value print by accessing an element 0 using Atomics load() method.
1 Initial value : 60
2 A previous value is : 60
3 A previous value is : 57
4 A previous value is : 52
5 A previous value is : 44
6 A previous value is : 35
7 Result after subtraction : 30
Related options for your search