Accessing ImmutableJS OrderedSet() - immutable.js

Playing with ImmutableJS, documentation needs work and actual working examples.
const a = [["a"],["b"],["c"]]
const b = Immutable.List(a)
const c = Immutable.OrderedSet(a)
b.first() // => "a"
b.get(1) // => "b"
c.first() // => ["a"]
c.get(1) // => undefined !uh oh!
c.toList().get(1) // => "b" !indirect!
Question: How do I print out the 2nd element of .OrderedSet c without converting it to a .List or loop over the entire list?

You can do it such as:
// using some ES6 features
let ordSet = immutable.OrderedSet([1, 2, 3])
let iterator = ordSet[Symbol.iterator] // get iterator to the collection
iterator.next() // 1
iterator.next() // 2
iterator.next() // 3
This said, let me note that even if this is not the nicest syntax, from the point of performance, it is the best as it gets: OrderedSet does not provide random access to its elements, each element simply remembers its successor and predecessor. Therefore, getting n-th element requires n hops, whether immutable.js provides some fancy helper for it or not. AFAIK, such linked-list-like implementation of OrderedSet is inevitable, if add / delete should remain fast.

Related

Increasing Value of State Variable in ForEach loop for Progress Bar in React

I'm trying to figure out a way to build a progress bar with React. I have a forEach loop that iterates through an array of about 7,000 indexes. Each time I validate a row, I want to update a state variable with percentage completion (and render this on the page live). I've tried iterating through these indexes, and updating my state variable (hoping to update the page) in the loop but I'm realizing that will not work. I obviously can't do this with a normal variable as it will reset when the component re-renders. Can anyone give me some insight on this topic?
Thanks.
Here is a code snippet from what I'm looking at:
parsedAssets.forEach(asset => {
newAssetValidated = validateBulkUpload(asset, parsedAssets, assetList, accountLogged, jobSites);
!newAssetValidated.reject_err ? validatedAssetList.accepted.push(newAssetValidated) : validatedAssetList.rejected.push(newAssetValidated);
setStateAssets({ ...stateAssets, validatedAssetList });
});
}
So essentially, as each asset is either accepted or rejected we add it to "stateAssets", and I'm hoping to build the progress bar from the length of the combined arrays that are getting set in stateAssets. However, when the forEach loop is completed, only the last validated asset is getting set due to it not updating until the forEach loop is completed.
Personally I can't imagine such a heavy validation, that you need progress-bar, but anyway.
First solution is to separate validation itself from state update for progress-bar into separate "threads". But since JS is single threaded, you may use some tricks with setTimeout or setInterval functionality. It may be very tricky, and in general not recommended practice with React.
Another way is - to set the work into queue & process 1 item at a time.
As an example I would do it something like this:
function ComponentWithProgress({parsedAssets, setParsedAssets}) {
const [validatedAssetList, setValidatedAssetList] = useState([])
const [progress, setProgress] = useState(0)
const [toDo, setToDo] = useState([])
if(parsedAssets && parsedAssets.length>0) {
setToDo(parsedAssets)
// clear parsedAssets in parent component to: [], false, null ...
// so you put it into toDo only once
setParsedAssets([])
}
if(toDo.length > 0) {
const asset = toDo[0]
const newToDo = toDo.slice(1) // All but 0th element
const newAssetValidated = validateBulkUpload(asset);
setValidatedAssetList([ ...validatedAssetList, newAssetValidated ]);
setToDo(newToDo)
setProgress( newToDo.length / ( validatedAssetList.length + newToDo.length ) * 100 )
}
// ... Render here
// If you need only accepted
const accepted = validatedAssetList.filter(v => !v.reject_err)
}
This example maybe not work for you as is, because you didn't showed us the context, but the main idea is here.

Multiple Variable Assignment in Javascript/GAS - Is this the most compact way to do it?

Ok so I have a spreadsheet which we extract a 2d array of values from.
But really I want one variable per line of this 2d array.
The following code does work... but is this the best way to do it?
function testAssignments(){
config = ss.getRange("C2:C6").getValues();//2D Array
result = []
config.forEach(x => result.push(x[0]))
var [a,b,c,d,e] = result;
console.log(a,b,c,d,e);
}
I also tried the line config.forEach(x=> x=x[0]) but that didn't work for some reason.
Use .flat instead of .forEach and .push. If you want a different variable name for each element, there isn't a better way.
const [a,b,c,d,e] = ss.getRange("C2:C6").getValues().flat();//1D Array
//or
const [[a],[b],[c],[d],[e]] = ss.getRange("C2:C6").getValues();

Node-red - need a multi-input function for a number value

So I'm just getting to grips with node-red and I need to create a conditional global function.
I have two separate global.payloads set to a number value of either 0 or 1.
What I need to happen now is, if global.payload is equal to value 1 then follow this flow, if it is equal to value 0 then follow this one.
I'm just a little confused with the syntax for the function statement. Any help gratefully appreciated.
Since you haven't accepted the current answer, thought I'd give this a try.
I think this is what you need to handle inputs from two separate global contexts. I'm simulating them here with two separate inject nodes to demonstrate:
The checkconf inject node emits a 1 or a 0. Same for the meshstatus node. Substitute your real inputs for those inject nodes. The real work is done inside the function:
var c = context.get('c') || 0; // initialize variables
var m = context.get('m') || 0;
if (msg.topic == "checkconf") // update context based on topic of input
{
c = {payload: msg.payload};
context.set("c", c); // save last value in local context
}
if (msg.topic == 'meshstatus') // same here
{
m = {payload: msg.payload};
context.set('m', m); // save last value in local context
}
// now do the test to see if both inputs are triggered...
if (m.payload == 1) // check last value of meshstatus first
{
if (c.payload == 1) // now check last value of checkconf
return {topic:'value', payload: "YES"};
}
else
return {topic:'value', payload: "NO"};
Be sure to set the "topic" property of whatever you use as inputs so the if statements can discriminate between the two input. Good luck!
You can use the Switch node to do this, rather than a Function node.

D3 Line Generator Handling Multiple Arrays

I have 3 arrays within a JSON file of the following structure:
I am trying to parse a JSON file of coordinate data into something that can be read by D3 path/line generators. I first had to find a way to ensure the values were actual numbers and not strings. A full discussion can be found here:
D3/JS mapping a JSON data callback
That discussion prompted me to not only consider formatting the JSON data via .map() to numbers, but also consider a nested/zipped format that the line generator can make sense of. That is really the target I've been after all along. As depicted above, My JSON has 3 arrays, xs, ys and id. id only governs color, and takes 1 of 3 values (0,1,2). I was recommended this approach:
var obj = raw_json[0];
var data = obj.id.map((id, i) => [+id, +obj.xs[i], +obj.ys[i]]);
My line generator function is:
var valueLine = d3.svg.line()
.x(function(d) {return xScale(d.xs);})
.y(function(d) {return yScale(d.ys)});
However I am getting tens of thousands of errors, and unfortunately I do not have that much experience with parsing related issues and I am not sure how to proceed.
Full block & JSON here.
Glad to see you took my advice on restructuring your data as we are moving in the right direction. I suggested that you should convert your three separate arrays into one array of individual arrays per point to make the use of the line generator more easy and to eliminate the need for cross-array reads to collect data for the points.
This time, though, you are not accessing your values correctly. By using function(d) { return xScale(d.xs); } you are assuming that your points were represented by objects having properties xs and ys. My suggested approach however got rid of these properties by storing the information into arrays. There are basically two ways around this:
Adjust you path generator's .x() and .y() callbacks while keeping your data structure.
var obj = raw_json[0];
var data = obj.id.map((id, i) => [+id, +obj.xs[i], +obj.ys[i]]);
// Remember, that d is a point's array [id, x, y]
var valueLine = d3.svg.line()
.x(function(d) { return xScale(d[1]); })
.y(function(d) { return yScale(d[2]); });
If you prefer to store your points' data in objects instead, another solution would be to adjust how your data is built.
// Structure data into an array of objects {id, x, y}
var obj = raw_json[0];
var data = obj.id.map((id, i) => ({
id: +id,
x: +obj.xs[i],
y: +obj.ys[i]
}));
// Keep your code as d now has properties x and y.
var valueLine = d3.svg.line()
.x(function(d) { return xScale(d.x); })
.y(function(d) { return yScale(d.y); });
I think you aren't modeling correctly the data to use to use with data(data).enter() and/or d3.svg.line(). As you defined your valueLine function it expects an array of objects with xs and ys properties and you are feeding it with an array of arrays.
Try it out manually to see how it works
valueLine([{xs: 1, ys: 1}, {xs: 3, ys: 5}, {xs: 12, ys: 21}])
and see the generated svg path:
"M100,400L300,-400L1200,-3600"
So maybe you can change how you are preparing your data for something like :
var data = obj.id.map((id,i) => ({id: +id, xs:+obj.xs[i], ys: +obj.ys[i]}));

Splice then re-index array in ActionScript 3

I want to remove the first four indexes from the array using splice(), then rebuild the array starting at index 0. How do I do this?
Array.index[0] = 'one';
Array.index[1] = 'two';
Array.index[2] = 'three';
Array.index[3] = 'four';
Array.index[4] = 'five';
Array.index[5] = 'six';
Array.index[6] = 'seven';
Array.index[7] = 'eight';
Array.splice(0, 4);
Array.index[0] = 'five';
Array.index[1] = 'six';
Array.index[2] = 'seven';
Array.index[3] = 'eight';
I am accessing the array via a timer, on each iteration I want to remove the first four indexes of the array. I assumed splice() would remove the indexes then rebuild the array starting at 0 index. it doesn't, so instead what I have done is created a 'deleteIndex' variable, on each iteration a +4 is added to deleteIndex.
var deleteIndex:int = 4;
function updateTimer(event:TimerEvent):void
{
Array.splice(0,deleteIndex);
deleteIndex = deleteIndex + 4;
}
What type of object is "Array" in the code you have shown? The Flash Array object does not have a property named "index". The Array class is dynamic, which means that it let's you add random properties to it at run time (which seems to be what you are doing).
In any case, if you are using the standard Flash Array class, it's splice() method updates the array indexes automatically. Here is a code example that proves it:
var a:Array = [1,2,3,4,5];
trace("third element: ", a[2]); // output: 3
a.splice(2,1); // delete 3rd element
trace(a); // output: 1,2,4,5
trace(a.length); // ouput: 4
trace("third element: ", a[2]); // output: 4
If I am understanding what you want correctly, you need to use the unshift method of Array.
example :
var someArray:Array = new Array(0,1,2,3,4,5,6,7,8);
someArray.splice(0,4);
somearray.unshift(5,6,7,8);
Also, you are using the Array Class improperly, you need to create an instance of an array to work with first.
The question is confusing because you used Array class name instead of an instance of an array. But as the commenter on this post said, if you splice elements, it automatically re-indexes.
im not sure what you want to do, but Array=Array.splice(0,4) should fix somethin..