calling function within module that is imported to another class - javascript

I am new to JavaScript (working my way through some basic tutorials). Can someone tell me what I am doing wrong here? I am trying to get the run function to reference the withinCircle function, then export the whole thing to another file so I can reference the run function. Feel free to modify my code anyway you want- I tried to follow "best" practices but I may have screwed up. Thanks!
var roleGuard = {
/** #param {Creep} creep **/
run: function(creep)
{
var target = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {filter: { owner: { username: 'Invader' } }});
if(target!=null)
{
console.log(new RoomPosition(target.pos.x,target.pos.y,'sim'));
//ranged attack here
//within 3, but further than 1
if(creep.pos.getRangeTo(target)<=3&&creep.pos.getRangeTo(target)>1)
{
creep.rangedAttack(target);
console.log("ranged attacking");
}
}
else
{
var pp=withinCircle(creep,target,3,'sim');
console.log(pp);
creep.moveTo(pp);
}
}
//------------------------------------------------------------
//move to closest point within z units of given evenmy
withinCircle: function(creep,target,z,room)
{
var targets = [new RoomPosition(target.pos.x-z,target.pos.y-z,room), new RoomPosition(target.pos.x+z,target.pos.y-z,room),new RoomPosition(target.pos.x-z,target.pos.y+z,room),new RoomPosition(target.pos.x+z,target.pos.y+z,room)];
var closest = creep.pos.findClosestByRange(targets);
return(closest);
}
//------------------------------------------------------------
};
module.exports = roleGuard;
Other file contains:
var roleGuard = require('role.guard');

for example:
// foo.js
function add(a,b){
return a + b
}
module.exports = add
and in the other file:
// bar.js
const add = require("./foo");
console.log(add(1,1))
those paths are relative to the file location. extension can be omitted.
you'll need node or browserify or webpack to make exports/require to work properly.
if you want a better explanation about modular javascript, look there, even if you not enter in the browserify world it will present you to what we can do nowadays.
EDIT:
in order to export more symbols you can do the following:
// foo2.js
function add(a,b){
return a + b
}
function multiply(a,b){
return a * b
}
module.exports = {
add:add,
multiply:multiply
}
And then in the consumer:
// bar2.js
const add = require("./foo2").add
const multiply = require("./foo2").multiply
//...
This is also valid:
// foo3.js
function add(a,b){
return a + b
}
exports.add = add
function multiply(a,b){
return a * b
}
exports.multiply = multiply
Consumer will need no relevant alteration:
// bar3.js
const add = require("./foo3").add
const multiply = require("./foo3").multiply
//...
If using babel/es6 modules have a different idion, which you can check there.

Related

if can't access parameter in JavaScript module

Hi I'm having problems with the scope of an if in a JavaScript module.
Here is a mock up of my code :
module.exports = {
caser(nb){
if(0 === 0){
nb = 3+2
}
}
}
The function is called from another JavaScript file. Nb however doesn't change when I do this.
My editor (visual studio code) marked nb as unused. This I tried :
module.exports = {
caser(nb){
let number = nb
if(0 === 0){
number = 3+2
}
}
}
This still doesn't seem to alter the value of nb. Does anyone know a solution to this problem?
Thanks in advance.
Reassigning nb (or number) will only change what those variable names point to in the current function. It sounds like what you need to do is return the changed value, and have the consumer of the function use it to reassign the value it passes in. Something like:
// consumer file:
const { caser } = require('./foo');
let nb = 5;
nb = caser(nb);
module.exports = {
caser(nb) {
if (0 === 0) {
nb = 3 + 2
}
return nb;
}
}
The only way to avoid having to reassign in the consumer would be for the consumer to pass an object instead, and mutate the object.
// consumer file:
const { caser } = require('./foo');
const objToPass = { nb: 5 };
caser(objToPass);
module.exports = {
caser(objToPass) {
if (0 === 0) {
objToPass.nb = 3 + 2
}
}
}

How to add keyword to acorn or esprima parser

I am working on a language that transpiles to javascript and has a similar syntax. However I want to include some new type of block statements. For syntax purposes they are the same as an IfStatement. How can I get esprima or acorn to parse this program MyStatement {a=1;} without throwing an error? Its fine if it calls it an IfStatement. I would prefer not to fork esprima.
It turns out, that the plugin capabilities of acorn are not really documented. It seems like forking acorn would be the easiest route. In this case, it is as simple as searching for occurances of _if and following a similar pattern for _MyStatement.
However it is possible to write a plugin to accomplish what I was trying to do. It seems a bit of a hack, but here is the code. The basic steps are:
To exend Parse and add to the list of keywords that will be recognized by the first pass
Create a TokenType for the new keyword and add it to the Parser.acorn.keywordTypes, extend parseStatement so that it processes the new TokenType
Create a handler for the new TokenType which will add information to the Abstract Syntax Tree as required by the keyword functionality and also consume tokens using commands like this.expect(tt.parenR) to eat a '(' or this.parseExpression() to process an entire expression.
Here is the code:
var program =
`
MyStatement {
MyStatement(true) {
MyStatement() {
var a = 1;
}
}
if (1) {
var c = 0;
}
}
`;
const acorn = require("acorn");
const Parser = acorn.Parser;
const tt = acorn.tokTypes; //used to access standard token types like "("
const TokenType = acorn.TokenType; //used to create new types of Tokens.
//add a new keyword to Acorn.
Parser.acorn.keywordTypes["MyStatement"] = new TokenType("MyStatement",{keyword: "MyStatement"});
//const isIdentifierStart = acorn.isIdentifierStart;
function wordsRegexp(words) {
return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
}
var bruceware = function(Parser) {
return class extends Parser {
parse(program) {
console.log("hooking parse.");
//it appears it is necessary to add keywords here also.
var newKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this const class extends export import super";
newKeywords += " MyStatement";
this.keywords = wordsRegexp(newKeywords);
return(super.parse(program));
}
parseStatement(context, topLevel, exports) {
var starttype = this.type;
console.log("!!!hooking parseStatement", starttype);
if (starttype == Parser.acorn.keywordTypes["MyStatement"]) {
console.log("Parse MyStatement");
var node = this.startNode();
return this.parseMyStatement(node);
}
else {
return(super.parseStatement(context, topLevel, exports));
}
}
parseMyStatement(node) {
console.log("parse MyStatement");
this.next();
//In my language, MyStatement doesn't have to have a parameter. It could be called as `MyStatement { ... }`
if (this.type == tt.parenL) {
node.test = this.parseOptionalParenExpression();
}
else {
node.test = 0; //If there is no test, just make it 0 for now (note that this may break code generation later).
}
node.isMyStatement = true; //set a flag so we know that this if a "MyStatement" instead of an if statement.
//process the body of the block just like a normal if statement for now.
// allow function declarations in branches, but only in non-strict mode
node.consequent = this.parseStatement("if");
//node.alternate = this.eat(acornTypes["else"]) ? this.parseStatement("if") : null;
return this.finishNode(node, "IfStatement")
};
//In my language, MyStatement, optionally has a parameter. It can also by called as MyStatement() { ... }
parseOptionalParenExpression() {
this.expect(tt.parenL);
//see what type it is
console.log("Type: ", this.type);
//allow it to be blank.
var val = 0; //for now just make the condition 0. Note that this may break code generation later.
if (this.type == tt.parenR) {
this.expect(tt.parenR);
}
else {
val = this.parseExpression();
this.expect(tt.parenR);
}
return val
};
}
}
process.stdout.write('\033c'); //cls
var result2 = Parser.extend(bruceware).parse(program); //attempt to parse
console.log(JSON.stringify(result2,null,' ')); //show the results.

How to pass integer values in cucumber test and verify the result

How do I call a simple addition function and assert the result of two values using selenium-cucumber-js framework with a test written below. While running the below it says
TypeError: TypeError: Cannot read property 'addvalues' of undefined
at createWorld.When (C:\Tests\cucumber\step-definitions\addvalues-steps.js:5:25)
Feature:
Scenario: Addition of two values
When Add two values 5 and 10
Then I should get result 15
// Here is my 'addvalues-steps.js' file
const expect = require('chai').expect;
module.exports = function () {
this.When(/^Add two values (-?\d+) and (-?\d+)$/, (x, y) =>{
this.page.addvalues.addValues(x,y);
})
this.Then(/^I should get result (-?\d+)$/, (ans) =>{
let tot = this.page.addvalues.addValues(x, y);
expect(tot).to.be.eql(ans);
})
};
// Following is my 'addvalues.js file'
module.exports = {
addValues(x,y){
var total = x + y ;
return total ;
}
};
// world.js >>
const { CustomWorld } = require('cucumber')
function CustomWorld() {
console.log('overriding the world')
this.page = {
addvalues: require('../page-objects/addvalues')
}
console.log("This is the recent error log:"+this.page.addvalues)
}
module.exports = function() {
this.World = CustomWorld;
Note: the below example is for an old version of cucumber-js: 1.3.3.
With cucumber.js, when you're referencing this from inside step definitions, you're actually referencing the World context. So, for this.page.addvalues.addValues(x,y); to work properly, you'll first need to create page that has a reference to your addvalues.js. Something along these lines:
world.js:
function CustomWorld() {
console.log('overriding the world')
this.page = {
addvalues: require('../page-objects/addvalues')
}
}
module.exports = function() {
this.World = CustomWorld;
};
addvalues.js:
//addvalues.js
module.exports = {
addValues(x,y){
var total = x + y ;
return total ;
}
};
There's also a couple of things to correct in your steps.js.
Don't pass arrow functions into the steps, as this will remove the this context that you're setting in World.js.
If you want to share variables between steps (as you do in your example), you need to store them somewhere. One such place, again, would be the World context. Note how in my version I set this.prevResult
When the variables are injected into your steps, they are injected as strings. Note the parseInt() in my version.
addvalues-steps.js:
const expect = require('chai').expect;
module.exports = function() {
this.When(/^Add two values (-?\d+) and (-?\d+)$/, function (x, y) {
this.prevResult = this.page.addvalues.addValues(parseInt(x, 10), parseInt(y, 10));
})
this.Then(/^I should get result (-?\d+)$/, function (ans) {
let tot = this.prevResult;
expect(tot).to.be.eql(parseInt(ans, 10));
})
}
UPD: It turns out that the question is about selenium-cucumber-js, which is a framework on top of cucumber-js. Disregard the comments about the world.js.
According to selenium-cucumber-js docs, you don't need this to access the page objects in your step definitions:
Page objects are accessible via a global page object and are
automatically loaded from ./page-objects.
const expect = require('chai').expect;
module.exports = function() {
this.When(/^Add two values (-?\d+) and (-?\d+)$/, function (x, y) {
this.prevResult = page.addvalues.addValues(parseInt(x, 10), parseInt(y, 10));
})
this.Then(/^I should get result (-?\d+)$/, function (ans) {
let tot = this.prevResult;
expect(tot).to.be.eql(parseInt(ans, 10));
})
}

How to write the common.js style

I have two functions
myFuncs.js
function funcA(e){
console.log("FuncA:" + e);
}
function B(e){
console.log("FuncB:" + e);
}
I would like to make common.js style module for these.
However I have some basic question.
I have read some articles and try to understand standard method.
In this case,
I need to make two files separately for each function A and B?
Are these are correct??
in funcA.js
(function(definition){
funcA = definition();
})(function(){//
'use strict';
var funcA = function funcA(e){};
funcA.prototype = {
console.log("funcA"+ e);
}
return funcA;
});
in main.js
var funcA = require("funcA.js");
funcA.funcA("test");
You can put them in one module with
// myFuncs.js
exports.funcA = function(e){
console.log("FuncA:" + e);
}
// main.js
const myFuncs = require("./myFuncs")
myFuncs.funcA("test")
or export only one function
// funcA.js
module.exports = function(e){
console.log("FuncA:" + e);
}
// main.js
const funcA = require("./funcA")
funcA("test");
You need a relative path, because require("funcA") will look in node_modules. And module names are usually lowercase and dash separated.

How to build a namespace-like string using chained variables

This is a strange one, but I'm exploring it to see if it's possible.
Let's say that I have a .NET application where I am using PubSub. I want a way to define the topic string using chained objects (not functions). The goal is to allow me a way of defining strings that lets me to take advantage of Visual Studio's IntelliSense and reduce the likelihood of spelling errors.
Here's an example:
/* Manual way */
var topic = "App.Navigation.CurrentItem"
/* Desired Solution */
// ... define the objects here ...
var topic = App.Navigation.CurrentItem;
console.log(topic); // "App.Navigation.CurrentItem"
var topic2 = App.Footer.CurrentItem;
console.log(topic2); // "App.Footer.CurrentItem"
I'd like each object to be responsible for outputing it's own value, and have the chaining process responsible for joining itself to the previous chained object via a predefined separator (in my case, a period [.]).
I've been playing with JavaScript getter syntax, but I'm curious if there's a better way.
Has anyone done something like this before, and if so, how did you solve it?
You're requirements aren't totally clear to me, but are you looking for something like this?
function namespace(ns) { this._ns = ns; }
namespace.prototype.toString = function() {return this._ns};
namespace.prototype.extend = function(suffix) {
return new namespace(this._ns + "." + suffix)
};
Usage:
App = new namespace('App');
App.Navigation = App.extend('Navigation');
App.Navigation.CurrentItem = App.Navigation.extend('CurrentItem');
console.log(App.Navigation.CurrentItem.toString()); // "App.Navigation.CurrentItem"
This is what I ended up with after reviewing StriplingWarrior's answer:
function Namespace(name, config) {
if (typeof name === "object") {
config = name;
name = null;
}
config = config || {};
this._ns = name;
this.define(config);
}
Namespace.prototype.toString = function() { return this._ns };
Namespace.prototype.define = function(config, base) {
base = base || this;
for (key in config) {
var name = (base._ns) ? base._ns + "." + key : key;
base[key] = new Namespace(name);
base.define(config[key], base[key]);
}
return base;
};
Usage:
var App = new Namespace("App", {
Navigation: {
Items: {
Current: {}
}
},
Content: {},
Footer: {
Items: {
Current: {}
}
}
});
console.log(App.toString()); // App
console.log(App.Navigation.Items.Current.toString()); // App.Navigation.Items.Current
console.log(App.Footer.toString()); // App.Footer
I also wrote a convenience method to reduce the toString():
function NS(namespace) {
return namespace.toString();
}
console.log(NS(App.Navigation.Items.Current));
Thanks again to StriplingWarrior for the the help!

Categories