Meteor compare elements in array - arrays

I'm just beginning the adventure of a meteor, so I have a little problem
The database structure looks like this:
users have roles, the roles have subroles. I want to check whether the user has at least one of the subrole, which is a function argument as an array.
Here's the code:
userHasAllPermissions: function(permissionArray) {
var result = false;
var user = Meteor.user();
if (!user) return false;
permissionArray = ["Permission 0", "Permission 1", "Permission 99999"];
var rolesToSearch = _.keys(user.roles);
for (var i = 0; i < rolesToSearch.length; i++) {
var role = Meteor.roles.findOne({name: rolesToSearch[i]});
var subrole = role.subRoles;
for(var k = 0; k < permissionArray.length; k++)
{
if(_.include(_.some(subrole,permissionArray[k]))){
result = true;
console.log("Ok");
break;
}
console.log("Error")
}
}
return result;
}

OK, right off the bat:
On line 5, you seem to be overwriting your permissionArray function argument. Are you sure you want to do that?
Is user.roles an Object or an Array? I'd expect an array, but then _.keys(user.roles) doesn't make sense.
It would be way more efficient to use the $in mongo query to get the subroles, you can then iterate over the resulting cursor. In fact, perhaps you can use two $in query operators to get your result right away: Meteor.roles.find({name:{$in:rolesToSearch}, 'subRoles.$':{$in: permissionArray}}) It's hard to test this, but I'm guessing you can find a query like that - if it returns a result - should let your function return true.

user.roles is Ocject, user.roles have Array of subRoles

Related

Get two arrays, compare and remove duplicates in Google Apps Script

I have got two lists on a google spreadsheet: 'Existing Companies' and 'New Companies'.
I would like to compare the two and find out which unique entries in 'New Companies' do not exist in 'Existing Companies', get those entries and eliminate from 'New Companies' all other entries.
I have made the following script to do it:
function grabNewCompanies() {
// grab existing companies list from sheet into an array
var sh = SpreadsheetApp.openById("sheetID").getSheetByName("sheetName")
var row = sh.getDataRange().getLastRow()
var existingCompanies = sh.getRange(2,1,row - 1,1).getValues()
Logger.log(existingCompanies)
//grab new companies added
var sh = SpreadsheetApp.openById("sheetID").getSheetByName("sheetName")
var row = sh.getDataRange().getLastRow()
var newCompanies = sh.getRange(2,4,row - 1, 1).getValues()
Logger.log(newCompanies)
var array = [];
for(i=0; i<newCompanies.length; i++) {
for(j=0; j<existingCompanies.length; j++) {
if(newCompanies[i][0] !== existingCompanies[j][0]) {
array.push([newCompanies[i][0]]);
}
Logger.log(array)
}
I have ran this script but it has failed.
The two arrays (existingCompanies and newCompanies) are returned correctly.
However, the comparison between the two does not seem to be working: it always returns the first element of the newCompanies array, regardless of whether it exists in existingCompanies.
Also, I am unsure about how to ensure that the values pushed into array are not duplicated if newCompanies contains more than one entry which does not exist in existingCompanies.
Thank you.
You want to retrieve the difference elements between existingCompanies and newCompanies. If my understand for your question is correct, how about this modification? I think that there are several solutions for your situation. So please think of this as one of them.
Modification points:
In the case that your script is modified, it picks up an element from newCompanies and it checks whether that is included in existingCompanies.
If that picked element is not included in existingCompanies, the element is pushed to array. In this modification, I used true and false for checking this.
This flow is repeated until all elements in newCompanies are checked.
Modified script 1:
When your script is modified, how about this?
From:
var array = [];
for(i=0; i<newCompanies.length; i++) {
for(j=0; j<existingCompanies.length; j++) {
if(newCompanies[i][0] !== existingCompanies[j][0]) {
array.push([newCompanies[i][0]]);
}
}
}
To:
var array = [];
for(i=0; i<newCompanies.length; i++) {
var temp = false; // Added
for(j=0; j<existingCompanies.length; j++) {
if(newCompanies[i][0] === existingCompanies[j][0]) { // Modified
temp = true; // Added
break; // Added
}
}
if (!temp) array.push([newCompanies[i][0]]); // Modified
}
Logger.log(array)
Modified script 2:
As other patterns, how about the following 2 samples? The process cost of these scripts are lower than that of the script using for loop.
var array = newCompanies.filter(function(e) {return existingCompanies.filter(function(f) {return f[0] == e[0]}).length == 0});
Logger.log(array)
or
var array = newCompanies.filter(function(e) {return !existingCompanies.some(function(f) {return f[0] == e[0]})});
Logger.log(array)
If I misunderstand your question, please tell me. I would like to modify it.

Removing records that exist in an array from ExtJS store

I have a store and an array. I want to remove records from the store if that record's value matches with values in the array. Following is is the code I am trying but it's not working. Can anyone suggest the correct way?
'store' is the actual store and 'filterItems' is the array of records I want to remove from 'store'.
store.each(function (record) {
for (var i = 0; i < filterItems.length; i++) {
if (record.get('ItemId') === _filterItems[i].get('ItemId')) {
itemIndex = store.data.indexOf(record);
store.removeAt(itemIndex );
}
}
});
Not sure about your code because i dont know all variables. Though its recommended to use the store.getRange() fn and iterate the array via for loop. Its better for performance.
var storeItems = store.getRange(),
i = 0;
for(; i<storeItems.length; i++){
if(Ext.Array.contains(filterItemIds, storeItems[i].get('id')))
store.remove(store.getById(storeItems[i].get('id')));
}
Here is an example which i tried right now and it works well.
https://fiddle.sencha.com/#fiddle/8r2
Try using the remove method of the store (docs)
store.remove(filterItems);
var indexes = [], i = 0;
dataviewStore.each(function(item, index){
if(item) {
if(item.data.columnId == columnId) {
indexes[i++] = index;
}
}
}, this);
dataviewStore.remove(indexes);
this is my example if your record is matches with the value then store the index of that item after storing indexes of all the items and remove them.
Otherwise you have to use for loop and remove them from end of the array.

Arrays and if statements. How to check if value is in array? *javascript*

So I have a program that sends emails. The user has a list of emails that cannot be sent to. These are in arrays and I need to use a if statement to determine if what the user entered in is in the array of emails. I tried the in function which didnt work but Im probably just using it wrong. I tried for loops and if statements inside. But that didnt work either. Here is a snapshot of the code Im using to help you get the idea of what im trying to do.
function test2(){
var safe = [1]
safe[1] = "lol"
safe[2] = "yay"
var entry = "lol"
Logger.log("entry: " + entry)
for(i = 0; i < safe.length; i++){
if(entry == safe[i]){
Logger.log("positive")
}else{
Logger.log("negative")
}
}
}
Here is what I tried with the in function to show you if I did it wrong
function test(){
var safe = [1]
safe[1] = "lol"
safe[2] = "yay"
var entry = "losl"
Logger.log("entry: " + entry)
if(entry in safe){
Logger.log("came positive")
}else{
Logger.log("came negative")
}
Logger.log(safe)
}
array.indexOf(element) > -1 usually does the trick for these situations!
To expand upon this:
if (array.indexOf(emailToSendTo) < 0) {
// send
}
Alternatively, check this cool thing out:
emailsToSend = emailsToSend.filter(function(x) {
// basically, this returns "yes" if it's not found in that other array.
return arrayOfBadEmails.indexOf(x) < 0;
})
What this does is it filters the list of emailsToSend, making sure that it's not a bad email. There's probably an even more elegant solution, but this is neat.

Select random elements from an array without repeats?

edit: I can't believe I didn't catch this sooner. Turns out my problem was re-declaring my first variables over and over again, essentially starting the program fresh instead of continuing it. To fix it, I replaced the first two lines with this:
if (initialized === undefined) {
trace("INITIALIZING");
var MCs = [];
var lastPos = "intializer";
var initialized = 1;
}
Now it works like a charm. I feel like a noob for this one; sorry to anyone whose time I wasted. I'd post this as an answer to my own question, but it won't let me since I'm still new.
Original Post follows:
I'm trying to make a flash that will randomly choose an ad, play it, and then randomly play another. To that end, I've succeeded by shuffling an array, and then gotoAndPlay-ing the label in the first element of the array, and then removing that element. At the end of each ad is gotoAndPlay(1); with all the main code being on the first frame. If the array is empty, it rebuilds it and reshuffles it.
The problem is, I don't want it to repeat any ads until its run through all of them; I think I've got that down, but I'm not positive. Further, I don't want the last element in the array to be the same as the first in the new one, so the same ad won't ever show twice in a row. I'm trying to have it detect if the element it just used matches the one it's about to use, and reshuffle if that happens, but in my testing it continues to occasionally show the same ad twice in a row.
I'm obviously doing something wrong, but being entirely new to ActionScript3 (and in fact to flash) I'm having a lot of trouble identifying what it is. Here's what I have right now:
var MCs = [];
var lastPos = "intializer";
if (MCs.length == 0) {
MCs = reset();
if (lastPos == MCs[0]) {
while (lastPos == MCs[0]) {
MCs = reset();
}
}
}
if (MCs.length > 0) {
lastPos = MCs[0];
MCs.splice(0,1);
gotoAndPlay(lastPos+"MC");
}
function reset(){
var PrepMCs = new Array("Image1", "Image2", "Image3");
var WorkMCs = new Array(PrepMCs.length);
var randomPos:Number = 0;
for (var i:int = 0; i < WorkMCs.length; i++)
{
randomPos = int(Math.random() * PrepMCs.length);
WorkMCs[i] = PrepMCs.splice(randomPos, 1)[0];
}
return WorkMCs;
}
Personally, I'd rather just do this with JavaScript, HTML, and images; it'd be really simple. But for hosting/CMS reasons I don't have any control over, I'm limited to a single file or a single block of code; I can't host anything externally, which as far as I can tell leaves Flash as my best option for this.
Any help would be greatly appreciated, thanks! If I've done something horribly, horribly wrong, and it's a wonder this even runs at all, don't hesitate to tell me!
edit: It just occurred to me, it is perfectly fine if the second run is in the same order as the first run, etc. The main thing is, it needs to be random. This is probably much easier to implement.
edit 2: MASSIVE DERP HERE. Every time it runs, it re-initializes MCs and lastPos... in other words, it's shuffling every time and starting over. What I should be researching is how to only run a line of code if a variable hasn't been initialized yet.
Blatantly stealing from #32bitKid, this is my version.
The main problem I have with his solution is the push/splice idea. As much as possible, I like to create once, and reuse. Shrinking and growing arrays is bulky, even if effective.
Also, this method does not re-order the array, which may or may not be valuable.
BTW, I like the way that he prevents a repeat of the previous item ("almost empty").
So here is another method:
package
{
public class RandomizedList
{
private var _items:Array;
private var idxs:Array;
private var rnd:int;
private var priorItemIdx:int;
private var curIdx:int;
public function RandomizedList(inarr:Array)
{
items = inarr;
}
private function initRandomize():void
{
idxs = new Array();
//Fisher-Yates initialization (http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle):
idxs[i] = 0;
for (var i:int = 1; i < items.length; i++)
{
rnd = int(Math.random() * (i + 1));
idxs[i] = idxs[rnd];
idxs[rnd] = rnd;
}
curIdx = 0;
priorItemIdx = -1;
}
private function randomize():void
{
var tempint:int;
//Fisher-Yates (http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle):
for (var i:int = items.length; i >= 1; i--)
{
rnd = int(Math.random() * (i + 1));
tempint = idxs[i];
idxs[i] = idxs[rnd];
idxs[rnd] = tempint;
}
curIdx = 0;
}
public function next():void
{
if (curIdx >= idxs.length)
{
randomize();
}
if (items.length > 1 && priorItemIdx == idxs[curIdx])
{
curIdx++;
}
priorItemIdx = idxs[curIdx++];
return items[priorItemIdx];
}
public function get items():Array
{
return _items;
}
public function set items(value:Array):void
{
_items = value;
initRandomize();
}
}
}
I would use a utility class like this to abstract out the behavior I wanted:
import flash.text.TextField;
class Randomizer {
private var unused:Array = [];
private var used:Array;
public function Randomizer(playList:Array) {
used = playList;
}
public function next():* {
// If almost empty, refill the unused array
if(unused.length <= 1) refill();
// Get the first item off the playList
var item:* = unused.shift();
// Shove it into the bucket
used.push(item);
// return it back
return item;
}
public function refill():void {
var i:int;
// Fisher-Yates shuffle to refill the unused array
while(used.length > 0) {
i = Math.floor(Math.random() * used.length)
unused.push(used.splice(i,1)[0])
}
}
}
Notice that it refills the unused array when the unused array still has one item in it, this makes it impossible for the last result to repeat twice in a row. This will return each item once before before looping, and will never repeat the same item twice.
You would use it by saying something like:
var ads:Randomizer = new Randomizer(["Image1", "Image2", "Image3"]);
ads.next(); // will return something
ads.next(); // will return something
ads.next(); // will return something
ads.next(); // will return something
// Keep going into infinity...
There is a little test example of this code working here.
See if this makes any sense
//create your array of all your ad names/frame labels
var PrepMCs:Array = new Array("Image1", "Image2", "Image3");
var shuffledMCs:Array = [];
//store the name of the last played ad in this var
var lastAdPlayed:String;
//shuffle the array
shuffleArray(PrepMCs);
function shuffleArray(arrayToShuffle:Array):void {
//clear the array
shuffledMCs = [];
var len:int = arrayToShuffle.length;
for(var i:int = 0; i<len; i++) {
shuffledMCs[i] = arrayToShuffle.splice(int(Math.random() * (len - i)), 1)[0];
}
//test to see if the new first ad is the same as the last played ad
if (lastAdPlayed == shuffledMCs[0]) {
//reshuffle
shuffleArray(PrepMCs);
} else {
lastAdPlayed = [0];
trace(shuffledMCs);
playAds();
}
}
//after each ad has played, call this function
function playAds():void {
if (shuffledMCs.length > 0) {
gotoAndPlay(shuffledMCs[0]);
shuffledMCs.splice(0,1);
} else {
//array is empty so we have played all the ads
shuffleArray(PrepMCs);
}
}

How would I remove a "row" in an array depending on the value of an element?

Here's what I'm currently doing/trying to do to accomplish my goal. But it is not removing the "row" the way I would like it too.
So, I'm making an object, then pushing it into an array. And the adding to the array part works fine and just as I expect.
var nearProfileInfoObj:Object = new Object();
nearProfileInfoObj.type = "userInfo";
nearProfileInfoObj.dowhat = "add";
nearProfileInfoObj.userid = netConnection.nearID;
nearProfileInfoObj.username = username_input_txt.text;
nearProfileInfoObj.sex = sex_input_txt.selectedItem.toString();
nearProfileInfoObj.age = age_input_txt.selectedItem;
nearProfileInfoObj.location = location_input_txt.text;
nearProfileInfoObj.headline = headline_input_txt.text;
theArray.push(nearProfileInfoObj);
So after that later on I need to be able to remove that object from the array, and it's not working the way I'm expecting. I want to take a variable whoLeft and capture their ID and then look in the array for that particular ID in the userid part of the object and if its there DELETE that whole "row".
I know you can do a filter with an array collection but that doesnt actually delete it. I need to delete it because I may be adding the same value again later on.
whoLeft = theiruserIDVariable;
theArray.filter(userLeaving);
public function userLeaving(element:*, index:int, arr:Array):Boolean
{
if (element.userid == whoLeft)
{
return false;
}
else
{
return true;
}
}
But this doesnt seem to be deleting the whole row like it implies. Does anyone know what i'm doing wrong?
Instead of modifying the original array, the new filtered array is returned by the filter method. So you need to assign the returned array to theArray.
Try this
theArray = theArray.filter(userLeaving);
EDIT This turned out to be slower than for loop:
An alternative to the hand coded loop could be something like this:
theArray.every(searchAndDestroy);
public function searchAndDestroy(element:*, index:int, arr:Array):Boolean
{
if (element.userid == whoLeft)
{
arr.splice(index,1);
return false;
}
return true;
}
As far as I know, every() terminates the first time the test function returns false. So the question is: for a big list, which is faster, the for loop or the loop that every() does with the overhead of the test function call.
EDIT #2 But this was faster than a for loop for a test I ran on an array of a million Points:
for each(var element:Object in theArray)
{
if (element.userid==whoLeft)
{
theArray.splice(theArray.indexOf(element),1);
break;
}
}
I think this is what you're looking for:
for(var i:uint = 0, len:uint = theArray.length; i<len; i++)
{
if(thisArray[i].id == whoLeft.id)
{
thisArray.splice(i, 1);
break;
}
}
However, do you really need it in an Array because you could always use a Dictionary which would mean accessing it by id which would be a lot simpler to remove.

Resources