Java-style Set collection for Javascript - javascript

I need a Set that has the API similar to the Set in Java.
This implementation:
http://jsclass.jcoglan.com/set.html
Requires the use of RequireJS, which requires my Java brain to twist too much at the moment.
Posting a function that is the functionality for Set would be a great answer.
Or a link to a Google Set or some other tech giant who has created this code already.
What about Google's Closure? The name confused me but it has a set.

In my opinion whatever java.util.Set can achieve can be done using simple javascript object. I don't see why you need additional library:
// empty set
var basket = {};
// adding object to set
basket['apple'] = true;
basket['banana'] = true;
basket['orange'] = true;
basket['apple'] = true;
// iterating through set contents, should print:
// apple
// banana
// orange
for(var fruit in basket)
console.log(fruit);
// check if an element exist
if(basket['pineapple']) {
console.log('has pineapple');
} else {
console.log('no pineapple');
}
// remove element from set
delete basket['apple'];

Related

Javascript not setting this to value with apply or call

Edit: the code below was made up on the spot to show how I was going about what I was doing. It definietely won't run, it is missing a lot of things.
Here is a working example in codepen: https://codepen.io/goducks/pen/XvgpYW
much shorter example: https://codepen.io/goducks/pen/ymXMyB
When creating a function that is using call or apply, the this value stays null when using getPerson. however, when I use apply or call with getPerson it returns the correct person.
Please critique, I am really starting to learn more and more. I am in the middle of a project section so it might be hard to change all the code, but my next project could implement this better.
call and apply are setting to the window and not the object.
I will provide code that is much simpler with the same concept of what I am talking about.
function createPerson(){
this.manager = null;
this.teamManager = null;
this.setTeamManager = function(val){
this.teamManager = val;
}
this.setManager = function(val){
console.log('setting manager to',val);
this.teamManager = val;
}
this.getTeamManager = function(){
console.log('setting team manager to',val);
return this.teamManager ;
}
this.getManager = function(){
return this.manager;
}
this.appendSelect = function(elem){
var that = this;
createOtherSelects(that,elem);
}
//some functions that create selects with managers etc
//now assume there are other selects that will filter down the teams,
//so we might have a function that creates on change events
function createOtherSelects(that){
//code that creates locations, depending on location chosen will
//filter the managers
$('#location').on('change',function(){
//do some stuff
//... then call create management
createManagement(that,elem);
});
}
function createManagement(that,elem){
var currentLocation = that.location; //works
var area = that.area;//works ... assume these are set above
//code that returns a filter and unique set of managers back
that.teamManager = [...new Set(
data.map(person=>{
if(person.area==area &&
person.currentLocation==currentLocation
){
return person;
}
})
)].filter(d=>{if(d){return d}});
if(elem.length>0){
var selectNames = ['selectManager','selectTeamManager'];
var fcns = [that.setManager,that.setTeamManager];
for(var i = 0; i < selectNames.length;i++){
//do stuff
if(certainCriteriaMet){
// filter items
if(filteredManager == 1){
fcns[i].call(null,currentManager);//
}
}
}
}
}
}
var xx = new createPerson()
In console I see setting manager and setting team manager to with the correct values.
however when I call xx in console, I see everything else set except for
xx.teamManager and xx.manager
instead it is applying to the window, so if I type teamManager in the console, it will return with the correct person.
If I straight up say
that.setManager('Steve')
or even it works just fine.
xx.setManager('steve')
the this value in setManager is somehow changing from the current instance of the object to this window. I don't know why, and I would like to learn how to use apply and call using that for future reference.
I think the issue is with your following code
fcns[i].call(null,currentManager)
If you are not supplying "this" to call, it will be replaced with global object in non-strict mode.
fcns[i].call(that,currentManager)
See mdn article here
From your codepen example, you need to change that line
fcnset[0].apply(that,[randomName]);
The first argument of the apply method is the context, if you are not giving it the context of your method it's using the global context be default. That's why you end up mutating the window object, and not the one you want !

Using localStorage and sessionStorage as tree of elements

During application refactoring I very lately found out about localStorage and sessionStorage are key-value storages, so question: is thee any JavaScript implementation for using localStorage, sessionStorage as JSON, and stay ability to easely edit them via browser debug tools?
Example:
We create some value for key application, it have sub-keys like settings, connection, they have subkeys for properties.
So, easy way to interact them like this:
if (localStorage.application.connection.URI.slice(0, 5) === "https") { ... }
And, if we need to destroy branch for properties and re-init them:
localStorage.application.connection = undefined;
Any way to do this? I know, I can use
if (localStorage.getItem("application.connection.URI").slice(0, 5) === "https") { ... }
And (thx to this answer How to remove localStorage data starting with a certain string?)
for (key in localStorage) {
if (key.substring(0,22) == 'application.connection') {
localStorage.removeItem(key);
}
}
But it is slightly hard to read and use.
Any suggestions? And sorry for my english.
A bit late but here you go: I implemented DotStorage as a hacky solution for this about a year ago.
It's neither maintained nor fully tested but it does the job.
...I just checked the repo: be aware that you need pako for this to work....
Don't use it for big things though as this is realized by automatically wrapping objects and their properties in proxies - implementing deep change detection by trapping everything.
Usage: like any other Javascript object, it's just persistent:
dotStorage.Hello = "World";
// reload page
console.assert(dotStorage.Hello == "World");
You can take a look at my JSFiddle based test file here
Example:
var myObj = {"New": "object"};
// save the object
dotStorage.refTest = myObj;
// get proxified instance
myObj = dotStorage.refTest;
// change nested properties
myObj.New = {"nested": {"otherObject": [0, 1]}};
console.log(JSON.stringify(dotStorage.refTest.New));
// reload the page ------------------------------------------
// change more nested properties
myObj.New.nested = 2;
// everything is still there
console.log(JSON.stringify(dotStorage.refTest.New));

How to make Screeps find sources?

In Screeps, I this code doesn't work:
var sources = creep.room.find(Game.FIND_SOURCES_ACTIVE);
It says this:
Cannot read property 'find' of undefined
I have been looking around and cannot find ANY other way to find sources.
Also I've noticed that most of other peoples code doesn't work and even the tutorial's code no longer works when put into the real game.
I can't be completely sure about your issue since I don't have your complete code to go off of but one issue could be that creepis not defined.
You need somewhere in your code to define creep such as a for loop to loop over each of your creeps in the game or room.
var roleMiner = require('role.miner') // role.miner being the module name for miner actions
for(var name in Game.creeps) {
var creep = Game.creeps[name];
//
// do whatever you wish with the current selected creep.
//
// most of the time you will call a module similar to what the tutorials suggest and put your actions for it in there
//
if(creep.memory.role == 'miner'){
roleMiner.run(creep); // passes the current selected creep to the run function in the module
}
}
So, in your roleMiner module you would have something that defines your miners actions.
var roleMiner = {
run: function(creep) {
// this one returns an array of the sources that are in the room with the creep
var sourcesRoom = creep.room.find(FIND_SOURCES);
// this one returns the source object which is closest to the creeps positon
var sourcesClose = creep.pos.findClosestByRange(FIND_SOURCES);
}
}
module.exports = roleMiner;
Hope this helps.
Screeps have some ... mechanism when sharing your data between each game tick.
If you store any thing in global Memory object, your data will lose all its prototype.
to restore your prototype use Object.setPrototypeOf(creep,Creep.prototype) or create new Creep object from your creep id.
I think what you are looking for is:
var sources = creep.pos.findClosestByRange(Game.SOURCES);
or
var sources = creep.pos.findClosestByPath(Game.SOURCES);
im a new player, not sure my code is efficient, i think the find method will be like this:
var sources = creep.room.find(FIND_SOURCES_ACTIVE)
creep will going to the active resource to harvester.

New Element in MooTools by UID

Is it possible to instantiate an element on Mootools based on the automatic UID that mootools create?
EDIT: To give more info on what is going. I'm using https://github.com/browserstate/history.js to make a history within an ajax page. When I add a DOM element to it (which does not have an id), at some point it passes through a JSON.toString methods and what I have of the element now is just the uid.
I need to recreate the element based on this UID, how could I go about doing that? Do I need to first add it to the global storage to retrieve later? If so, how?
in view of edited question:
sorry, I fail to understand what you are doing.
you have an element. at some point the element is turned into an object that gets serialised (all of it? prototypes etc?). you then take that data and convert to an object again but want to preserve the uid? why?
I don't understand how the uid matters much here...
Using global browser storage also serialises to string so that won't help much. Are we talking survival of page loads here or just attach/detach/overwrite elements? If the latter, this can work with some tweaking.
(function() {
var Storage = {};
Element.implement({
saveElement: function() {
var uid = document.id(this).uid;
Storage[uid] = this;
return this;
}
});
this.restoreElement = function(uid) {
return Storage[uid] || null;
}
})();
var foo = document.id("foo"), uid = foo.uid;
console.log(uid);
foo.saveElement().addEvent("mouseenter", function() { alert("hi"); } );
document.id("container").set("html", "");
setTimeout(function() {
var newElement = restoreElement(uid);
if (newElement)
newElement.inject(document.body);
console.log(newElement.uid);
}, 2000);
http://jsfiddle.net/dimitar/7mwmu/1/
this will allow you to remove an element and restore it later.
keep in mind that i do container.set("html", ""); which is not a great practice.
if you do .empty(), it will GC the foo and it will wipe it's storage so the event won't survive. same for foo.destroy() - you can 'visually' restore the element but nothing linked to it will work (events or fx).
you can get around that by using event delegation, however.
also, you may want to store parent node etc so you can put it back to its previous place.

Dojo extending dojo.dnd.Source, move not happening. Ideas?

NOTICE: THIS IS SOLVED, I WILL PUBLISH THE SOLUTION HERE ASAP.
Hey all,
Ok... I have a simple dojo page with the bare essentials. Three UL's with some LI's in them. The idea si to allow drag-n-drop among them but if any UL goes empty due to the last item being dragged out, I will put up a message to the user to gie them some instructions.
In order to do that, I wanted to extend the dojo.dnd.Source dijit and add some intelligence. It seemed easy enough. To keep things simple (I am loading Dojo from a CDN) I am simply declating my extension as opposed to doing full on module load. The declaration function is here...
function declare_mockupSmartDndUl(){
dojo.require("dojo.dnd.Source");
dojo.provide("mockup.SmartDndUl");
dojo.declare("mockup.SmartDndUl", dojo.dnd.Source, {
markupFactory: function(params, node){
//params._skipStartup = true;
return new mockup.SmartDndUl(node, params);
},
onDndDrop: function(source, nodes, copy){
console.debug('onDndDrop!');
if(this == source){
// reordering items
console.debug('moving items from us');
// DO SOMETHING HERE
}else{
// moving items to us
console.debug('moving items to us');
// DO SOMETHING HERE
}
console.debug('this = ' + this );
console.debug('source = ' + source );
console.debug('nodes = ' + nodes);
console.debug('copy = ' + copy);
return dojo.dnd.Source.prototype.onDndDrop.call(this, source, nodes, copy);
}
});
}
I have a init function to use this to decorate the lists...
dojo.addOnLoad(function(){
declare_mockupSmartDndUl();
if(dojo.byId('list1')){
//new mockup.SmartDndUl(dojo.byId('list1'));
new dojo.dnd.Source(dojo.byId('list1'));
}
if(dojo.byId('list2')){
new mockup.SmartDndUl(dojo.byId('list2'));
//new dojo.dnd.Source(dojo.byId('list2'));
}
if(dojo.byId('list3')){
new mockup.SmartDndUl(dojo.byId('list3'));
//new dojo.dnd.Source(dojo.byId('list3'));
}
});
It is fine as far as it goes, you will notice I left "list1" as a standard dojo dnd source for testing.
The problem is this - list1 will happily accept items from lists 2 & 3 who will move or copy as apprriate. However lists 2 & 3 refuce to accept items from list1. It is as if the DND operation is being cancelled, but the debugger does show the dojo.dnd.Source.prototype.onDndDrop.call happening, and the paramaters do look ok to me.
Now, the documentation here is really weak, so the example I took some of this from may be way out of date (I am using 1.4).
Can anyone fill me in on what might be the issue with my extension dijit?
Thanks!
If you use Dojo XD loader (used with CDNs), all dojo.require() are asynchronous. Yet declare_mockupSmartDndUl() assumes that as soon as it requires dojo.dnd.Source it is available. Generally it is not guaranteed.
Another nitpicking: dojo.dnd.Source is not a widget/dijit, while it is scriptable and can be used with the Dojo Markup, it doesn't implement any Dijit's interfaces.
Now the problem — the method you are overriding has following definition in 1.4:
onDndDrop: function(source, nodes, copy, target){
// summary:
// topic event processor for /dnd/drop, called to finish the DnD operation
// source: Object
// the source which provides items
// nodes: Array
// the list of transferred items
// copy: Boolean
// copy items, if true, move items otherwise
// target: Object
// the target which accepts items
if(this == target){
// this one is for us => move nodes!
this.onDrop(source, nodes, copy);
}
this.onDndCancel();
},
Notice that it has 4 arguments, not 3. As you can see if you do not pass the 4th argument, onDrop is never going to be called by the parent method.
Fix these two problems and most probably you'll get what you want.
In the end, I hit the Dojo IRC (great folks!) and we ended up (so far) with this...
function declare_mockupSmartDndUl(){
dojo.require("dojo.dnd.Source");
dojo.provide("mockup.SmartDndUl");
dojo.declare("mockup.SmartDndUl", dojo.dnd.Source, {
markupFactory: function(params, node){
//params._skipStartup = true;
return new mockup.SmartDndUl(node, params);
},
onDropExternal: function(source, nodes, copy){
console.debug('onDropExternal called...');
// dojo.destroy(this.getAllNodes().query(".dndInstructions"));
this.inherited(arguments);
var x = source.getAllNodes().length;
if( x == 0 ){
newnode = document.createElement('li');
newnode.innerHTML = "You can drag stuff here!";
dojo.addClass(newnode,"dndInstructions");
source.node.appendChild(newnode);
}
return true;
// return dojo.dnd.Source.prototype.onDropExternal.call(this, source, nodes, copy);
}
});
}
And you can see where I am heading, I put in a message when the source is empty (client specs, ug!) and I need to find a way to kill it when something gets dragged in (since it is not, by definition, empty any more ona incomming drag!). That part isnt workign so well.
Anyway, the magic was not to use the onDnd_____ functions, but the higher level one and then call this.inherited(arguments) to fire off the built in functionality.
Thanks!
dojo.require("dojo.dnd.Source");
dojo.provide("mockup.SmartDndUl");
dojo.declare("mockup.SmartDndUl", dojo.dnd.Source, {
Dojo require statement and declare statement are next to next. I think that will cause dependencies problem.
the dojo require statement should go outside onload block and the declare statement should be in onload block.

Categories