I'm trying to assign an object to the property of another object.
That is model of the real project. Here, I have a race, with an array of cars, which have an driver property. The driver property is an object. At the console output, I want to have a car with the name of the driver.
<script>
let carsNames = ["Ferrari", "Mercedes", "Maserati", "Renault"];
let drivers = ["Ayrton", "Alain", "Michael", "Nikki"];
let Car = (function (_team, _driver) {
let team = _team;
let driver = _driver;
return {
getTeam: function () {
return team;
},
getDriver: function () {
return driver;
}
}
});
let Driver = (function (_name) {
let name = _name;
return {
getName: function () {
}
}
});
let Race = (function () {
cars = [];
for (let i = 0; i < carsNames.length; i++) {
driver = new Driver(drivers[i]);
car = new Car(carsNames[i], driver);
cars.push(car);
}
return {
getCars: function () {
return cars;
}
}
});
let GPSyldavie = new Race();
let myrace = GPSyldavie.getCars();
myrace.forEach(function (mr) {
console.log(mr.getTeam(), mr.getDriver().getName());
})
// Console output :
// Ferrari undefined
// Mercedes undefined
// Maserati undefined
// Renault undefined
</script>
The point is to bind a driver with a car, but somewhere I fail to tell to the car that it is driven by a driver.
You're getName function does not return anything...
let Driver = (function (_name) {
let name = _name;
return {
getName: function () {
}
}
});
Should look more like...
let Driver = (function (_name) {
let name = _name;
return {
getName: function () {
return name;
}
}
});
Related
I’m developing a basic TodoList based on a tutorial of DAppUviersity on Youtube using Ethereum Blockchain, Solidity, and truffle , and I found this error when excepting the creatTask function, I tried every solution without any result, Any help, please
app.js Code:
App = {
web3Provider: null,
contracts: {},
init: async function () {
await App.initWeb3();
},
initWeb3: async function () {
if (typeof web3 !== "undefined") {
App.web3Provider = web3.currentProvider;
web3 = new Web3(web3.currentProvider);
} else {
App.web3Provider = new Web3.providers.HttpProvider(
"http://localhost:7545"
);
web3 = new Web3(App.web3Provider);
}
return App.initContract();
},
initContract: async function () {
$.getJSON("TodoList.json", function (TodoList) {
const todoList = TodoList;
App.contracts.TodoList = TruffleContract(TodoList);
App.contracts.TodoList.setProvider(App.web3Provider);
return App.render();
});
},
render: async function () {
if (App.loading) {
return;
}
App.setLoading(true);
App.account = web3.eth.accounts[0];
$("#account").html("Your Account: " + App.account);
const todoList = await $.getJSON("TodoList.json");
App.contracts.TodoList = TruffleContract(todoList);
App.contracts.TodoList.setProvider(App.web3Provider);
App.todoList = await App.contracts.TodoList.deployed();
App.setLoading(false);
return App.renderTask();
},
renderTask: async () => {
const taskCount = await App.todoList.taskCount();
const $taskTemplate = $(".taskTemplate");
const submitButton = $("#submitButton");
for (var i = 1; i <= taskCount; i++) {
const task = await App.todoList.tasks(i);
const taskId = task[0].toNumber();
const taskContent = task[1];
const taskCompleted = task[2];
const $newTaskTemplate = $taskTemplate.clone();
$newTaskTemplate.find(".content").html(taskContent);
$newTaskTemplate
.find("input")
.prop("name", taskId)
.prop("checked", taskCompleted)
.on("click", App.toggleCompleted);
if (taskCompleted) {
$("#completedTaskList").append($newTaskTemplate);
} else {
$("#taskList").append($newTaskTemplate);
}
$newTaskTemplate.show();
submitButton.show();
}
},
createTask: async () => {
try {
App.setLoading(true);
const task = $("#newTask").val();
console.log(task);
await App.todoList.addTask(task);
window.location.reload();
} catch (error) {
console.log(error);
}
},
setLoading: function (boolean) {
App.loading = boolean;
const loader = $("#loader");
const content = $("#content");
if (boolean) {
loader.show();
content.hide();
} else {
loader.hide();
content.show();
}
},
};
$(function () {
$(window).load(function () {
App.init();
});
});
Solidity Code:
pragma solidity 0.5.16;
contract TodoList {
uint256 public taskCount = 0;
struct Task {
uint256 id;
string description;
bool complete;
}
event TaskCreated(uint256 id, string content, bool completed);
mapping(uint256 => Task) public tasks;
constructor() public {
addTask("Morning Coffee");
}
function addTask(string memory _description) public {
taskCount++;
tasks[taskCount] = Task(taskCount, _description, false);
emit TaskCreated(taskCount, _description, false);
}
}
Hello Everyone,
I’m developing a basic TodoList based on a tutorial of DAppUviersity on Youtube using Ethereum Blockchain, Solidity, and
truffle , and I found this error when excepting the creatTask
function, I tried every solution Hello Everyone,
I’m developing a basic TodoList based on a tutorial of DAppUviersity on Youtube using Ethereum Blockchain, Solidity, and
truffle , and I found this error when excepting the creatTask
function, I tried every solution
I have an array that has 3 contacts. I want the same person's name to be deleted when I click on the delete button, but unfortunately I do not know where the problem is that it does not work.
I have two functions in this program, one removeContact to perform the delete operation
And I have a function called showrecords to get the content of the array and display the name and number of contacts with a dedicated delete button for each contact
In this program, I used the pattern builder pattern
Please guide me to the conclusion to solve the problem of not being deleted
Please click on the show Person button to test the program. Contacts will be displayed and click on the delete button. You will see that the delete operation is not performed.
function ElementBuilder(name) {
this.element = document.createElement(name);
this.appendSelector = function(selector) {
this.appendElement = document.querySelector(selector).appendChild(this.element);
return this
};
this.setAttribute = function(attribute, valueAttribute) {
this.element.setAttribute(attribute, valueAttribute)
return this;
};
this.addEventListener = function(event, fun) {
this.element.addEventListener(event, fun);
return this;
};
this.text = function(text) {
this.element.textContent = text;
return this;
};
this.build = function() {
return this.element;
};
}
const builder = {
create: function(name) {
return new ElementBuilder(name);
}
};
function PhoneBook() {
this.records = [{ name: "niloufar", phone: 1111 }, { name: "sara", phone: 2222 }, { name: "sara", phone: 3333 }];
// function remove
this.removeContact = function() {
const self = this
function removePerson(item) {
if (item.target.classList.contains('delbutton')) {
const remID = item.target.getAttribute('data-id');
self.records.splice(remID, 1);
}
}
return removePerson;
}
}
function Render(container) {
this.container = container;
const phoneBook = new PhoneBook();
const remove = phoneBook
.removeContact();
this.removeEntry = (item) => {
remove(item); //
this.showrecords();
}
this.init = function() {
const btn = builder
.create("button")
.text("show person")
.addEventListener("click", this.showrecords)
.appendSelector("div")
.build();
};
// Function: Read contacts from the array and display them
this.showrecords = () => {
const addBookId = document.getElementById('phone-book-container');
let index = 0;
addBookId.innerHTML = '';
const arry = phoneBook.records;
arry.forEach(elm => {
const nameContent = builder
.create('p')
.text(`${elm.name}`)
.appendSelector("div")
.build();
const phoneContent = builder
.create('p')
.text(`${elm.phone}`)
.appendSelector("div")
.build();
const anchor = builder
.create('a')
.addEventListener('click', this.removeEntry)
.setAttribute('href', '#')
.setAttribute('class', 'delbutton')
.setAttribute("id", "deleteButton")
.text("delete")
.setAttribute('date-id', `${index}`)
.appendSelector("div")
.build();
});
}
}
const phoneBookContainer = document.getElementById("phone-book-container");
const app = new Render(phoneBookContainer);
app.init();
<div id="phone-book-container"></div>
You have to pass the item (which is actually the event object) to your function:
function ElementBuilder(name) {
this.element = document.createElement(name);
this.appendSelector = function(selector) {
this.appendElement = document.querySelector(selector).appendChild(this.element);
return this
};
this.setAttribute = function(attribute, valueAttribute) {
this.element.setAttribute(attribute, valueAttribute)
return this;
};
this.addEventListener = function(event, fun) {
this.element.addEventListener(event, fun);
return this;
};
this.text = function(text) {
this.element.textContent = text;
return this;
};
this.build = function() {
return this.element;
};
}
const builder = {
create: function(name) {
return new ElementBuilder(name);
}
};
function PhoneBook() {
this.records = [{ name: "niloufar", phone: 1111 }, { name: "sara", phone: 2222 }, { name: "sara", phone: 3333 }];
// function remove
this.removeContact = function() {
const self = this
function removePerson(item) {
if (item.target.classList.contains('delbutton')) {
const remID = item.target.getAttribute('date-id');
self.records.splice(remID, 1);
}
}
return removePerson;
}
}
function Render(container) {
this.container = container;
const phoneBook = new PhoneBook();
const remove = phoneBook
.removeContact();
this.removeEntry = (item) => {
remove(item);
this.showrecords();
}
this.init = function() {
const btn = builder
.create("button")
.text("show person")
.addEventListener("click", this.showrecords)
.appendSelector("div")
.build();
};
// Function: Read contacts from the array and display them
this.showrecords = () => {
const addBookId = document.getElementById('phone-book-container');
addBookId.innerHTML = '';
const arry = phoneBook.records;
arry.forEach((elm, index) => {
const nameContent = builder
.create('p')
.text(`${elm.name}`)
.appendSelector("div")
.build();
const phoneContent = builder
.create('p')
.text(`${elm.phone}`)
.appendSelector("div")
.build();
const anchor = builder
.create('a')
.addEventListener('click', this.removeEntry)
.setAttribute('href', '#')
.setAttribute('class', 'delbutton')
.setAttribute("id", "deleteButton")
.text("delete")
.setAttribute('date-id', `${index}`)
.appendSelector("div")
.build();
});
}
}
const phoneBookContainer = document.getElementById("phone-book-container");
const app = new Render(phoneBookContainer);
app.init();
<div id="phone-book-container"></div>
I have several JavaScript files that I create enums. for example:
source.enum.js
const enumUtils = require('../enum.utils');
const EmailAddressesSourceType = enumUtils.createEnum([
['DIRECTORY', 'directory'],
['FILE', 'file'],
['ARRAY', 'array']
]);
module.exports = { EmailAddressesSourceType };
The enum.utils.js is just a file that do the simple function of creating an enum from array:
class EnumUtils {
constructor() { }
// This method takes a map of elements and converts them to freeze objects (an enum-like object).
createEnum(mapItems) {
if (!mapItems || mapItems.length <= 0) {
throw new Error(`No array received: ${mapItems} (1000000)`);
}
const mapList = new Map([...mapItems]);
const symbolMap = {};
mapList.forEach((value, key) => { symbolMap[key] = value; });
return Object.freeze(symbolMap);
}
}
const enumUtils = new EnumUtils();
module.exports = enumUtils;
Now since I have 5-6 js files with enums, I want to avoid 'const enumUtils = require('../enum.utils');' in each of them, and do it all together in index.js file, something like this:
const { EmailAddressStatus, EmailAddressType, SendEmailStepName } = require('./files/emailAddress.enum');
const { Placeholder } = require('./files/placeholder.enum');
const { EmailAddressesSourceType } = require('./files/sources.enum');
const { Mode, Status, Method } = require('./files/system.enum');
const { StatusIcon, Color, ColorCode } = require('./files/text.enum');
const createEnum = (mapItems) => {
if (!mapItems || mapItems.length <= 0) {
throw new Error(`No array received: ${mapItems} (1000000)`);
}
const mapList = new Map([...mapItems]);
const symbolMap = {};
mapList.forEach((value, key) => { symbolMap[key] = value; });
return Object.freeze(symbolMap);
};
module.exports = {
createEnum(Color), createEnum(ColorCode), createEnum(EmailAddressStatus), createEnum(EmailAddressType), createEnum(EmailAddressesSourceType),
createEnum(Method), createEnum(Mode), createEnum(Placeholder), createEnum(SendEmailStepName), createEnum(Status), createEnum(StatusIcon)
};
But, there are compilation error in:
module.exports = {
createEnum(Color), createEnum(ColorCode), createEnum(EmailAddressStatus), createEnum(EmailAddressType), createEnum(EmailAddressesSourceType),
createEnum(Method), createEnum(Mode), createEnum(Placeholder), createEnum(SendEmailStepName), createEnum(Status), createEnum(StatusIcon)
};
My question is, there is a workaround so enable me to reduce the 'const enumUtils = require('../enum.utils');' in each file of the enums js file?
Thanks!
UPDATE 1
The error I'm getting is this:
The current status of the file (before I was trying to refactor) - It works OK:
index.js
const { EmailAddressStatus, EmailAddressType, SendEmailStepName } = require('./files/emailAddress.enum');
const { Placeholder } = require('./files/placeholder.enum');
const { EmailAddressesSourceType } = require('./files/sources.enum');
const { Mode, Status, Method } = require('./files/system.enum');
const { StatusIcon, Color, ColorCode } = require('./files/text.enum');
module.exports = {
Color, ColorCode, EmailAddressStatus, EmailAddressType, EmailAddressesSourceType,
Method, Mode, Placeholder, SendEmailStepName, Status, StatusIcon
};
This guy, guy-incognito, solved for me the issue. Now it works like a charm. Thanks man!
const { EmailAddressStatus, EmailAddressType, SendEmailStepName } = require('./files/emailAddress.enum');
const { Placeholder } = require('./files/placeholder.enum');
const { EmailAddressesSourceType } = require('./files/sources.enum');
const { Mode, Status, Method } = require('./files/system.enum');
const { StatusIcon, Color, ColorCode } = require('./files/text.enum');
const createEnum = (mapItems) => {
if (!mapItems || mapItems.length <= 0) {
throw new Error(`No array received: ${mapItems} (1000000)`);
}
const mapList = new Map([...mapItems]);
const symbolMap = {};
mapList.forEach((value, key) => { symbolMap[key] = value; });
return Object.freeze(symbolMap);
};
module.exports = {
Color: createEnum(Color),
ColorCode: createEnum(ColorCode),
EmailAddressStatus: createEnum(EmailAddressStatus),
EmailAddressType: createEnum(EmailAddressType),
EmailAddressesSourceType: createEnum(EmailAddressesSourceType),
Method: createEnum(Method),
Mode: createEnum(Mode),
Placeholder: createEnum(Placeholder),
SendEmailStepName: createEnum(SendEmailStepName),
Status: createEnum(Status),
StatusIcon: createEnum(StatusIcon)
};
I have module executer that will be executed on every api request now i am trying to write cases to unit test that executer. I have promise that returns chain that is being executed based on response. I see issue executing promise in test case , any help here to proper test this use case will be apprecaited.
main.ts
export class Executor {
private passedParam: ILogParams = {} as ILogParams;
constructor(public identity: Identity) {
this._ajv = new Ajv();
}
public execute(moduleName: string): (param1, param2) => any {
const self = this;
// getting rid of the tslint issue with Function
return function(params: any, responseCallback: (param: any , param2: any) => any) {
let _mod;
let _httpRequest;
let _params;
Promise.resolve(getApiModule(self.identity, moduleName))
.then((mod: ModuleBase<any, any>) => {
_mod = mod;
mod.ExecStage = ExecStage.Init;
return mod.init(getHttpModule(self.identity), params);
})
.then((httpRequest: HttpRequestBase) => {
_httpRequest = httpRequest;
if (_mod.Response().Summary.Header) {
throw _mod.Response().Summary;
}
return httpRequest;
})
.then(() => {
// empty the error stack
_mod.objErrorHandler.RemoveAllError();
_mod.ExecStage = ExecStage.Before;
return _mod.before(params);
})
.then((params1: any) => {
const _validators = _mod.getValidators();
let _failed: boolean = false;
return params1;
})
.then((params2: any) => {
_params = params2;
_mod.ExecStage = ExecStage.Core;
return _mod.core(_params, _httpRequest);
})
.catch((data: any) => {
const error: IHeader = {} as IHeader;
})
.then((data: any) => {
responseCallback(data, moduleName.substr(moduleName.indexOf('/') + 1));
});
};
}
}
main.spec.ts
import * as sinon from "sinon";
import {ModuleExecutor} from "./main.ts";
import {ExecStage, Identity} from "../../src/ts/common/Enums";
import ValidateRequestSchema from "../../src/ts/validation/requestSchema.js";
describe("ModuleExecuter", () => {
const sandbox = sinon.createSandbox();
afterEach(function afterTests() {
sandbox.restore();
});
let executer;
let executerSpy;
let results;
let stubbedExecutor;
let apiModule;
let _this;
const stubbedExecutorReturnFuction = sandbox.spy(function(args) {
executer = new ModuleExecutor(Identity.node);
executerSpy = executer.execute();
_this = this;
return new Promise(function(resolve) {
// moduleExecutor.execute(params, callback function)
executerSpy(args, function(data) {
resolve(data.Details);
});
});
});
const stubbedExecutorReturn = sandbox.spy(function(args, innerFunc) {
return innerFunc({Details: successResponse});
});
beforeEach(function() {
stubbedExecutor = sandbox.stub(ModuleExecutor.prototype, "execute").callsFake(function() {
return stubbedExecutorReturn;
});
apiModule = new GetAccountBalance();
const execute = sandbox.spy(stubbedExecutorReturnFuction);
results = execute("Payments/accountBalance/GetAccountBalance", {test:"test"});
});
describe("ModuleExecutor", function() {
it('should call ModuleExecutor.execute', function () {
sinon.assert.calledOnce(stubbedExecutor);
});
it('should return a promise', function() {
results.then(function(data) {
expect(data).toBe(successResponse);
});
});
it('should check validate AJV schema', function() {
let _mod;
results.then((mod: ModuleBase<any, any>) => {
_mod = mod;
mod.ExecStage = ExecStage.Before;
const requestSchema = "I" + _mod.__proto__.constructor.name + "Param";
const classSchema = ValidateRequestSchema[requestSchema];
const valid = _this._ajv.validate(classSchema, {test:"test"});
console.log("BOOLEAN>>>>>>>", valid);
expect(valid).toBeTruthy();
});
});
});
});
Is it possible to test the code below with Jasmine testing tool or any other npm module like rewire or similar?
const AuthValidatorDumb = require('./src/AuthValidatorDumb');
const AuthValidator = require('./src/AuthValidator');
const config = require('../config');
let instance;
if (!instance) {
if (config.get('auth.enabled')) {
instance = AuthValidator;
} else {
instance = AuthValidatorDumb;
}
}
module.exports = instance;
I've got a variant for testing the code above.Suppose you have:
1) The code for index.js in the question above.
2) AuthValidator.js:
class AuthValidator {}
module.exports = AuthValidator;
3) AuthValidatorDumb.js:
class AuthValidatorDumb {}
module.exports = AuthValidatorDumb;
Here is test/index.spec.js:
const proxyquire = require('proxyquire');
const AuthValidator = require('../src/AuthValidator');
const AuthValidatorDumb = require('../src/AuthValidatorDumb');
describe('auth index', () => {
it('should return AuthValidator', () => {
const configMock = { get: () => 'sth' };
const Instance = proxyquire('../index', {
'../config': configMock,
});
expect(new Instance() instanceof AuthValidator).toBeTruthy();
});
it('should return AuthValidatorDumb', () => {
const configMock = { get: () => undefined };
const Instance = proxyquire('../index', {
'../config': configMock,
});
expect(new Instance() instanceof AuthValidatorDumb).toBeTruthy();
});
});