Passing Variable length array to function Node JS - javascript

Is there a way to call an addon function with a variable length. I take the user input into a variable that looks like
Uinput = [5,3,2];
Now i want to call my addon based on these numbers so it would be
addon.myaddon(5,3,2);
I also want to extend this to n inputs so if my variable of user inputs becomes
Uinput = [5,3,2,6,...,n];
then the addon will be called like
addon.myaddon(5,3,2,6,...,n);
addon.myaddon(Uinput) // will not seperate the inputs by commas are they are in the array variable, it treats the whole array as the input
This seems simple enough but it is giving me a bit of trouble. Any tips ?

Take a look at Function.prototype.apply
Uinput = [5,3,2,...,7]; // the last number in the array is in position 'n'
addon.myaddon.apply(null, Uinput);
This is equivalent to calling:
addon.myaddon(Uinput[0], Uinput[1], Uinput[2], ... , Uinput[n]);
Real example using Math.max:
// Basic example
Math.max(1,6,3,8,4,7,3); // returns 8
// Example with any amount of arguments in an array
var mySet = [1,6,3,8,4,7,3];
Math.max.apply(null, mySet); // returns 8

Related

Apply variable number of filter conditions to a javascript array while traversing it only once?

I have a javascript array of nested data that holds data which will be displayed to the user.
The user would like to be able to apply 0 to n filter conditions to the data they are looking at.
In order to meet this goal, I need to first find elements that match the 0 to n filter conditions, then perform some data manipulation on those entries. An obvious way of solving this is to have several filter statements back to back (with a conditional check inside them to see if the filter needs to be applied) and then a map function at the end like this:
var firstFilterList = _.filter(myData, firstFilterFunction);
var secondFilterList = _.filter(firstFilterList, secondFilterFunction);
var thirdFilterList = _.filter(secondFilterList, thirdFilterFunction);
var finalList = _.map(thirdFilterList, postFilterFunction);
In this case however, the javascript array would be traversed 4 times. A way to get around this would be to have a single filter that checks all 3 (or 0 to n) conditions before determining if there is a match, and then, inside the filter at the end of the function, doing the data manipulation, however this seems a bit hacky and makes the "filter" responsible for more than one thing, which is not ideal. The upside would be that the javascript Array is traversed only once.
Is there a "best practices" way of doing what I am trying to accomplish?
EDIT: I am also interested in hearing if it is considered bad practice to perform data manipulation (adding fields to javascript objects etc...) within a filter function.
You could collect all filter functions in an array and check every filter with the actual data set and filter by the result. Then take your mapping function to get the wanted result.
var data = [ /* ... */ ],
filterFn1 = () => Math.round(Math.random()),
filterFn2 = (age) => age > 35,
filterFn3 = year => year === 1955,
fns = [filterFn1, filterFn2, filterFn2],
whatever = ... // final function for mapping
result = data
.filter(x => fns.every(f => f(x)))
.map(whatever);
One thing you can do is to combine all those filter functions into one single function, with reduce, then call filter with the combined function.
var combined = [firstFilterFunction, seconfFilterFunction, ...]
.reduce((x, y) => (z => x(z) && y(z)));
var filtered = myData.filter(combined);

giving a different value to a variable on each different value from a JavaScript array

I have a JS array with more than a million entries.
I want JavaScript to assign a specific color to flag on every different value from the array
say that my Array contains this:
var foo = new Array([10,20,30,40,50,36,60,70,80,90,100]);
It is worth knowing that my array contains 58 different values.
I am trying to do something like this:
if (foo.every(10)) flag = "red";
if (foo.every(20)) flag = "yellow";
I need a way to do it for all the values in the array without having to repeat the line above 58 times.
note that I know that the flag will be overridden and the flag in my code is unique for every different value.
Also note that the array is imported as JSON data from a MySQL table using PHP, so any PHP approaches to this problem will also be appreciated.
Easy JS solution:
var numberToColorDictionary = {
10: "red",
20: "yellow"
...
}
// After this runs, 'flags' should contain all the right flags.
var flags = foo.map(function(number) {
return numberToColorDictionary[number];
});
Although, this does sound like you're querying your database wrong. If the numbers are ids from MySQL, you should use join to get the correct flags.
And by the way, you don't need the new Array syntax. just do:
var foo = [10,20,30,40,50,36,60,70,80,90,100];

Javascript equivalent of VBS redim preserve

I'm trying to rewrite some old VBScript as Javascript for an ASP.NET application and there is one line I'm not sure how to translate, and I'm not even entirely positive what it's doing.
The application essentially allows the user to enter in a new employee number to add to the database and then assign it user permissions. Don't ask me why the code is such a mess, I didn't write it originally, I'm just trying to make it work in Chrome
here's the relevant code that i've managed to translate so far:
if(form1.txtEmpno.value != ""){
var oOption;
oOption = document.createElement("OPTION");
oOption.text=form1.txtEmpno.value;
oOption.value=form1.txtEmpno.value;
form1.lstActive.add (oOption);
oOption = document.createElement("OPTION");
oOption.text="";
oOption.value="";
form1.lstPerms.add (oOption);
redim preserve arrUsers(1,ubound(arrUsers,2)+1);
arrUsers(0,ubound(arrUsers,2)) = form1.txtEmpno.value;
arrUsers(1,ubound(arrUsers,2)) = "";
form1.txtEmpno.value = "";
oOption = null;
}
here's the line in question:
redim preserve arrUsers(1,ubound(arrUsers,2)+1);
MSDN defines ReDim [Preserve] varname(subscripts) as:
The ReDim statement is used to size or resize a dynamic array that has already been formally declared using a Private, Public, or Dim statement with empty parentheses (without dimension subscripts). You can use the ReDim statement repeatedly to change the number of elements and dimensions in an array.
If you use the Preserve keyword, you can resize only the last array dimension, and you can't change the number of dimensions at all. For example, if your array has only one dimension, you can resize that dimension because it is the last and only dimension. However, if your array has two or more dimensions, you can change the size of only the last dimension and still preserve the contents of the array.
Arrays in JavaScript have different semantics to VBScript's arrays, especially in that they're actually closer to a vector than a true array, furthermore JavaScript does not provide for true N-dimensional arrays: instead you use staggered-arrays (arrays-within-arrays). Which means your VBScript cannot be syntactically converted to JavaScript.
Here's your relevant code in VBScript:
ReDim Preserve arrUsers(1,ubound(arrUsers,2)+1)
arrUsers(0,ubound(arrUsers,2)) = form1.txtEmpno.value
arrUsers(1,ubound(arrUsers,2)) = ""
We see that arrUsers is a 2-dimensional array. This will need to be converted into a staggered array, but you haven't posted the code that defines and initializes arrUsers, nor how it is used later on, so I can only work from making assumptions.
It looks to be adding 1 element to the last dimension, but the code only seems to use the extra space in the [1] subscript (i.e. it only wants the extra dimensional space for certain values of the 0th dimension instead of all values), which makes this simpler as you don't need to iterate over every 0th-dimension subscript.
JavaScript arrays have numerous function-properties that we'll use, in particular push: which appends an element to the end of an array (internally growing the buffer if necessary), and pop which removes the last (highest-indexed) element from an array (if an array is empty, it's a NOOP):
var arrUsers = [ [], [] ]; // empty, staggered 2-dimensional array
...
arrUsers[0].push( form1.txtEmpno.value );
arrUsers[1].pop();
Much simpler.
However, if this array is just part of some internal model to store and represent data then you should take advantage of JavaScript object-prototypes instead of using array indexes, as that makes the code self-describing, for example:
var User = function(empNo, name) {
this.employeeNumber = empNo;
this.name = name;
};
var users = [];
users.push( new User(1, "user 1") );
users.push( new User(23, "user 23") );
...
for(var i = 0; i < users.length; i++ ) {
alert( users[i].name );
}

How do I use #DbLookup results to populate a Readers field in xpages?

db = new Array("myserver", "myfolder\\mydb.nsf")
dir = getComponent("Dir").value;
div = getComponent("Div").value;
lu = #DbLookup(db, "ManagerAccess", dir + "PP" + div, "DTManagers");
var a = [];
a.push(lu);
var item:NotesItem = docBackEnd.replaceItemValue('FormReaders', #Unique(a));
item.setReaders(true);
That code is on the querySaveDocument ssjs. The result I get from the #DbLookup (when I put in a computed field) look like this:
Pedro Martinez,Manny Ramirez,David Ortiz,Terry Francona
I tried doing an #Explode(#Implode) thing on it, but it doesn't seem to work.
The error I get in the browser just tells me that the replaceItemValue line is broken.
To test it, I pushed several strings one at a time, and it worked correctly populating my FormReaders field with the multiple entries.
What am I doing wrong?
I see several problems here:
A. In cases as described by you #Dblookup in fact would return an array. If you push an array into a plain computedField control it will exactly look as that you wrote:
value1, value2, ..., valueN
A computedField doesn't know anything about multiple values etc, it just can display strings, or data that can be converted to strings.
If you want to test the return value you could try to return something like lu[0]; you then should receive the array's 1st element, or a runtime error, if lu is NOT an array. Or you could ask for the array's size using lu.length. That returns the number of array elements, or the number of characters if it's just a plain string.
B. your code contains these two lines:
var a = [];
a.push(lu);
By that you create an empty array, then push lu[] to the first element of a[]. The result is something like this:
a[0] = [value1, value2, ..., valueN],
i.e. a is an array where the first element contains another array. Since you don't want that, just use #Unique(lu) in your replaceItemValue-method.
C. I don't see why replaceItemValue would throw an error here, apart from what I wrote in topic B. Give it a try by writing lu directly to the item (first without #Unique). That should work.
D. for completeness: in the first line you used "new Array". A much better way to define your db parameters is
var db = ["myserver", "myfolder/mydb.nsf"];
(see Tim Tripcony's comment in your recent question, or see his blog entry at http://www.timtripcony.com/blog.nsf/d6plinks/TTRY-9AN5ZK)

javascript array show undefined when escape one index

I face a problem when tried to assign a value with a specific index. suppose I have javascript variable like
var track = new Array();
Now I assign a value for a specific index like-
track[10]= "test text";
now array has one value and it's length would be 1. But the main problem is it show it's length is 11.
alert(track.length); // 11 but I expect 1
and if I print its value then it shows like--
alert(track); // ,,,,,,,,,test text
and if I console this array then it show like below--
console.log(track); // undefined,undefined,undefined,undefined,.....,test text
I am very much confused because I assign only one value but it show 11. How it assign it's value and what characteristics array variable shows. Can anyone explain me and how to get its length 1 using below code--
var track = new Array();
track[10]= "test text";
alert(track); // test text
alert(track.length); // 1
console.log(track); // test text
The Array object automatically fills in the missing indexes. The reason it gives length 11 is because the index starts at 0.
If you are wanting to use key-value just use an object.
var track = {};
It will not have a .length value however.
javascript automatically fills in the array to push the element you want. You can get the "true" count by doing this:
track.filter(Boolean).length
However note that this will only "work" if you do not have any other elements that resolve to "false" value (eg. empty strings or setting them to false) so if you want to this, make sure you never actually set any other array elements to a falsy value so that you can use this convention. For example if you want to set other array values to a falsy value, use something like -1 instead as the thing to check.
Since you're setting the value for 10th position it's showing array size of 11
You must start from 0th position..
var track = new Array();
track[0]= "test text";
alert(track); // test text
alert(track.length); // 1
console.log(track); // test text
Try this
For such kind of operations i generally prefer the library called Underscore.js.
It abstracts array manipulations. You might want to checkout the compact method
Compact works like this:
_.compact([undefined, undefined, undefined, "test test"]) as ["test test"]
Then you can check the length of the returned array.
Though a simple approach is
filter(Boolean).length
But if you want to use the array then you might like underscore.

Categories