I am not able to move on to the next section since i could not understand how this works. For reference I will post the link.
http://eloquentjavascript.net/1st_edition/chapter7.html
var roads = {};
function makeRoad(from, to, length) {
function addRoad(from, to) {
if (!(from in roads))
roads[from] = [];
roads[from].push({to: to, distance: length});
}
addRoad(from, to);
addRoad(to, from);
}
I am totally lost to get the basic idea of this function. Anyone who is generous to help. Thank you in advance. you are always help me to unlock many concepts.
It works by defining a function inline (addRoad) and then calling it to add a road in each direction (from to to and then to to from).
addRoad maintains a data structure of roads:
"roads": [
"fromLocation" : [ "destination1", "destination2" ],
"fromLocation2" : [ "destination3" ]
]
addRoad first checks to see if the from location exists in the array of roads (that's the if (!(from in roads)) clause. If it doesn't exist then it creates an empty array to store future destinations. It can then add the destination to that array.
To create my example data structure above I could call addRoad as follows:
addRoad('fromLocation', 'destination1');
addRoad('fromLocation', 'destination2');
addRoad('fromLocation2', 'destination3');
Related
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.
I'm working with Dust.js and trying to use the dust.makeBase function to merge and render data from two arrays (datax and datay) in an newcontext variable.
var context = dust.makeBase();
var newcontext = context.push(datax)
.push(datay);
As Dust documentation the last array pushed (in my sample the datay) become the current context. Launching on jsFiddle i can see that data got from current context are displayed correctly.
Selfstorage Information
{#.}
{#data}{id} - {special_offer}
{/data}
{/.}
However when i came display data out of current context apparently the data is not reached. The following not work.
Selfstorage Facilities
{#.}
{#facility}
{id} - {size}
{#facilityamenities.amenities}{amenities_id} - {full_desc}
{/facilityamenities.amenities}
{/facility}
{/.}
I have got some instructions on http://www.dustjs.com/guides/contexts/ but it isn't enough.
Checking some examples on web i was trought context helpers and i came out with this version on jsfiddle and although a function code is executed the result isn't as expected. Below a piece of code.
var context = dust.makeBase({"getselfdata": {
"selfdata": function(chunk, context)
{
var price = context.get("facility.price_formatted");
return price;
}
}});
Any help is appreciate.
You are exactly correct that the last item pushed onto the context becomes the current context. If you push multiple items onto the context, there is no way to reference them by position, for example "the item pushed onto the context before this one".
If you provide Dust a reference that doesn't exist in the current context, Dust will search each previous context for the reference. This allows you to walk up the context stack.
I have made two changes to your example to get it to work. For datax, I wrapped the array in an object with one key, facilities:
{ "facilities": [
{ "facility": { ... } },
{ "facility": { ... } }
]}
Then, in your template, I told Dust to search for this reference:
{#facilities}
{#facility}
<tr><td>{id} - {size} - {#facilityamenities}{#amenities}
{amenities_id} - {full_desc}
{/amenities}{/facilityamenities}</td></tr>
{/facility}
{/facilities}
You had one additional bug in this template. For {#facilityamenities.amenities} to work, your data would need to look like this:
{ "facilityamenities": {
"amenities": { ... } }
However, your "facilityamenities" is an array, so instead you should use {#facilityamenities}{#amenities} so that Dust will first loop over facilityamenities, and then search for amenities.
With these changes your JSFiddle works as I believe you intend.
This is my working code: http://jsfiddle.net/spadez/5ntLetey/1/
It works perfectly but I'm trying to pull the remaining information into the fields. This is the code I had previously for the lat and long that I found online:
lat.val(results[0].geometry.location.lat());
lng.val(results[0].geometry.location.lng());
How can I pull the remaining information in? This is one example of what I tried and didn't work:
country_short.val(results[0].address_components.country());
Here is the API documentation, what am I doing wrong?
You're not doing anything particularly wrong, unfortunately the returned address components can vastly differ. For example if you were to geocode a coordinate set which might be in the middle of an ocean, you;'re not going to get many address components and perhaps nothing at all, whereas in the middle of somewhere like New York City there are many components that get returned.
What you need to do is to parse the returned response to find something you want like country and only insert that into your fields if and only if there is an address component that has a type of "country".
So for example to get country short and long you would do something like this:
// Get Country value.
var country = getCountry(results[0].address_components)
$('#country_long').val(country.long);
$('#country_short').val(country.short);
calling the function which looks something like this:
function getCountry(addressComponents) {
var returnCountry = {
'long': 'N/A',
'short': 'N/A'
};
// Loop through all address components and find country if possible.
$(addressComponents).each(function (componentIndex, component) {
// loop through all "types" of each component to find if there is a type of "country"
$(component.types).each(function (indexTypes, type) {
if (type == 'country') {
// Then return the long_name and short_name of the component
returnCountry.long = component.long_name;
returnCountry.short = component.short_name;
}
});
});
return returnCountry;
}
Demo: http://jsfiddle.net/5ntLetey/3/
I've searched through the myriad parent/child array/object/whatever questions here and elsewhere and haven't been able to solve my issue. I know this is a bit long, but I wanted to ensure I'm providing enough info to you guys.
Here's what I want to do:
I have a number of <div>-delineated items on the page with parent/child relationships, generated via php from my database
I want to use these items as the data source for a D3.js Dendrogram (a node-link tree diagram http://mbostock.github.com/d3/ex/cluster.html)
I'm storing them with left/right nested set values but also parentID values, so I can add ID, parentID, rgt, lft and depth attributes to the <div> elements, so I should have available whatever's needed to generate the parent/child relationships on the client side
For various reasons, instead of creating a JSON file on the server side to use as the data source, I need to create it on the client side based on the attributes in #3
I've had difficulty getting various suggested javascript functions to work and all the D3 examples I've found use either a preexisting JSON file or generated math-based file, not attributes of elements already on the page
Here is an example of what already works for me with the D3 Dendrogram, but it's not generated dynamically:
var tree3 =
{"sid": "1", "children": [
{"sid": "2", "children": [
{"sid": "5", "children": [
{"sid": "75"},
{"sid": "85", "children": [
{"sid": "87"}, ...
To give you an idea of where these attributes are in the DOM, I originally tried the below, but of course it doesn't generate any hierarchy:
function tree() {
var tree=[];
$("article").each(function(){
tree.push({
sid:$(this).attr("sid"),
l:$(this).attr("l"),
r:$(this).attr("r"),
pid:$(this).attr("pid")
});
});
return tree;
}
I've been messing around unsuccessfully with variants of the below to get a nested array:
function tree2() {
$("article").(function(d) {
return d.parent().attr("pid") === 0;
}, function(parent, child) {
return parent.attr("pid") === child.parent().attr("sid");
}).toArray();
}
So, I'm driving myself crazy trying to create the javascript array nested correctly, but it's dawned on me that I may not need to and that D3's data selectors and methods could be sufficient. Could you please help me with the code to:
Pull the needed attributes to generate the parent/child relationship within a D3 function ("sid" is the identifier) or, if this isn't possible,
Create the needed array or array-like object in javascript for use by D3 (still with "sid" as the identifier).
Thanks in advance.
You need to get recursive! Basically the trick is to pass the current parent in as you go, which changes the context and allows you to walk down the tree.
Update: Working fiddle.
Assuming your HTML structure is something like this:
<div sid="1" pid="">
<div sid="1.1" pid="1">
<div sid="1.1.1" pid="1.1">
</div>
</div>
</div>
You could do something like this:
var _json = {};
function addTreeNode(div, parentObj) {
var childObj = {
sid: $(div).attr("sid"),
pid: $(div).attr("pid")
}
// add this to it's parent in the JSON hierarchy
if (!parentObj.children) parentObj.children = [];
parentObj.children.push(childObj);
// keep adding for all children div's
$(div).find("div").each(function() {
addTreeNode(this, childObj);
});
}
// start at the roots, it will magically work it's way out to the leaves
$("body > div").each(function(){
addTreeNode(this, _json);
});
console.log(_json);
Note that if your tree is big enough, you will cause stack overflows, especially in IE. In that case, you'll need to switch this over from recursion to iteration. It's not as pretty that way, though.
right now i am at a point where i feel that i need to improve my javascript skills because i already see that what i want to realize will get quite complex. I've iterrated over the same fragment of code now 4 times and i am still not sure if it's the best way.
The task:
A user of a webpage can add different forms to a webpage which i call modules. Each form provides different user inputs and needs to be handled differently. Forms/Modules of the same type can be added to the list of forms as the user likes.
My current solution:
To make the code more readable and seperate functions i use namespaced objects. The first object holds general tasks and refers to the individual forms via a map which holds several arrays where each contains the id of a form and the reference to the object which holds all the functions which need to be performed especially for that kind of form.
The structure looks more or less similar to this:
var module_handler = {
_map : [], /* Map {reference_to_obj, id} */
init: function(){
var module = example_module; /* Predefined for this example */
this.create(module);
},
create: function(module) {
//Store reference to obj id in map
this._map.push([module,id = this.createID()]);
module.create(id);
},
createID: function(id) {
//Recursive function to find an available id
},
remove: function(id) {
//Remove from map
var idx = this._map.indexOf(id);
if(idx!=-1) this._map.splice(idx, 1);
//Remove from DOM
$('#'+id+'').remove();
}
}
var example_module = {
create: function(id) {
//Insert html
$('#'+id+' > .module_edit_inner').replaceWith("<some html>");
}
}
Now comes my question ;-)
Is the idea with the map needed?
I mean: Isn't there something more elegant like:
var moduleXYZ = new example_module(id)
which copies the object and refers only to that form.... Something more logical and making speed improvements?? The main issue is that right now i need to traverse the DOM each time if i call for example "example_module.create() or later on any other function. With this structure i cant refer to the form like with something like "this"???
Do you see any improvements at this point??? This would help me very much!!! Really i am just scared to go the wrong way now looking at all the stuff i will put on top of this ;-)
Thank You!
I think you're looking for prototype:
=========
function exampleModule(id)
{
this.id = id;
}
exampleModule.prototype.create = function()
{
}
=========
var module1 = new exampleModule(123);
module1.create();
var module2 = new exampleModule(456);
module2.create();