getting the value of static method in javascript class - javascript

i can't figure it out on how to get the values of a static method of a class. my code is below.
class Field {
constructor(rows = 11, cols = 10) {
this.numRows = rows
this.numCols = cols
}
static loadFromFileContents(contents) {
this.numCols = contents.split('x')[0]
this.numRows = contents.split('x')[1]
}
}
const contents = `4 x 5`
const field = Field.loadFromFileContents(contents)
console.log(field.numCols)
console.log(field.numRows)
first of all, i want to get the instance of the static method. something like this instanceof(field), it should be equal to 'Field'. but i don't know if my syntax is correct for getting the instance. Second i want the return value of field.numCols should be equal to 4 because of the first split value and
field.numRows should be equal to 5. sorry i'm not that familiar with static method of a class. i hope you can help me with my problem. thank you so much.

It sounds like the static method needs to parse the passed string and return a new Field instance:
class Field {
constructor(rows = 11, cols = 10) {
this.numRows = rows
this.numCols = cols
}
static loadFromFileContents(contents) {
const [rows, cols] = contents.split(' x ');
return new Field(rows, cols);
}
}
const contents = `4 x 5`
const field = Field.loadFromFileContents(contents)
console.log(field.numCols)
console.log(field.numRows)

Related

Function to format and add object to array not functioning properly

My component has a state array "bets" consisting of bet objects. The function in question creates an empty "records" array to house formatted records to be stored in the database.
const placeBets = () => {
//determine type of bet(s) - single,parlay,etc.
if(slipType === "single"){
let records = [];
bets.forEach(bet=>{
let tmpModel = formatSingleBet(bet)
records.push(tmpModel);
})
console.log(records);
}
}
I run a for each loop on the bets array to format each bet calling the formatSingleBet function.
//Function to format single bets in records for db storage
const formatSingleBet = (bet) =>{
//create instance of bet model obj and add properties
let betModel = model;
betModel.type = slipType;
betModel.wager = bet.wager;
betModel.odds = bet.odds.decimal;
betModel.result = "";
let legType = bet.type;
if(legType === "Spread"){
//create instance of spread line object
let spread = Spread;
spread.team.type = bet.team.type;
spread.team.name = bet.team.name;
spread.line = bet.handicap;
spread.result = "";
betModel.legs[0].fixtureID = bet.fixtureID;
betModel.legs[0].line = spread;
betModel.legs[0].odds = bet.odds.decimal;
}else if(legType === "3-Way Moneyline"){
//create instance of ML line object
let ml = ML;
ml.team.type = bet.team.type;
ml.team.name = bet.team.name;
ml.result = "";
betModel.legs[0].fixtureID = bet.fixtureID;
betModel.legs[0].line = ml;
betModel.legs[0].odds = bet.odds.decimal;
}else if(legType === "Total"){
//create instance of Total line object
let total = Total;
total.result = "";
total.bet = bet.bet;
total.line = bet.total;
betModel.legs[0].fixtureID = bet.fixtureID;
betModel.legs[0].line = total;
betModel.legs[0].odds = bet.odds.decimal;
}
return {
contestPlayerID: match.params.entryid,
jsonBet: betModel
};
}
I create an instance of the model object, and set the properties depending on the "leg type" of the bet. I then return the formatted bet to be inserted into the records array which is then returned.
The issue is that regardless of the differences in the bet, the betModel object is always returned as the last bet in the bets array.
One thing I noticed is that when I log the betModel it appears to be different for each bet, however the property values change when drilling into the object.
Please help, any advice would be wonderful.
By assigning betModel = model you are simply creating a reference to model and all the changes you make to betModel will also be made to model. This means that model is not a blank prototype, but contains the values of the last bet that you processed.
In order to use model as a prototype in the way you seem to intend use spread syntax to assign a copy to betModel.
let betModel = {...model}
const spreadSource = { a: 1, b: 2 };
const spread = {...spreadSource};
spread.c = 'Added'
console.log('spread: ', spread);
console.log('spreadSource: ', spreadSource);
const referenceSource = { a: 1, b: 2 };
const reference = referenceSource;
reference.c = 'Added';
console.log('reference: ', reference)
console.log('referenceSource: ', referenceSource)

array to ObjectList angular

import { Board } from './board';
export class Notification {
id : number ;
startDate : Date = null;
endDate : Date = null;
message : string = '';
notificationBoards: Board[] ;
}
Board class
export class Board {
id : number = 0;
name : string = '';
createDate : Date = null;
createdBy : number ;
}
Coponent class is
message.component.ts
///..
submitForm(obj) {
console.log("obj - "+obj);
let notificationObj:Notification = new Notification();
let selectedBoard: Board[];
notificationObj.startDate = obj.startDate;
notificationObj.endDate = obj.endDate;
notificationObj.message = obj.message;
notificationObj.notificationBoards = obj.board;
console.log("notificationObj.notificationBoards"+notificationObj.notificationBoards.length);
for (let i = 0; i < notificationObj.notificationBoards.length; i++) {
console.log(":::"+notificationObj.notificationBoards[i] +":::");
}
...///
I am able to add the notification but unable to add the board obj inside notification object. Board is a list of boards.
obj.board - is an array {10,20,...} which is boardId.
I want to add this array to Board[] and send to service layer.
let selectedBoard: Board[]; is the board list and I want to push notificationObj.notificationBoards[i] to selectedBoard[i] and so on.
Basicaly want to add array to object list Board[].Can someone please help.
Your obj.board is a plain array of numbers (boardIds as you explained), notificationObj.notificationBoards is an array of Board objects.
Typescript would not allow you to convert an object array of type Board class into an array of number values..
You'll have to map one array type to another something like this.
notificationObj.notificationBoards = obj.board.map(boardId=>{
let boardObj:Board = new Board();
boardObj.id = boardId; //since we have only one element (boardId), other fields of board object are not set.
return boardObj;
});
Thanks.

iterate through Json array and get nested object's value Typescript

I have an array with to access a list of properties which i have manage to get the value of these properties however, there is a nested object "Region" in the list which has a specific property "regionName" that i would like to retrieve the value, please check the code and uploaded images for reference.
I hope to this made sense. Thank You in advance
export function CreateStores(xhttp: XMLHttpRequest, storeArray?: Array<PromotionClasses.Store>) {
while (STORE_TABLE.rows.length > 1) {
STORE_TABLE.deleteRow(1);
}
if (storeArray == undefined) {
//Convert the response into an array of objects
storeArray = JSON.parse(xhttp.responseText) as Array<any>;
}
CheckForDuplicateStores(storeArray);
//Get the current row length of the table so we know where to append to
let tableRowLength = STORE_TABLE.rows.length as number;
console.log("Store array is");
// console.log(storesInPromotionArray);
for (let i = 0; i < storeArray.length; i++) {
//A dictionary containing the key value pair of the stores properties
let tableData = {};
//Add the store's id to the storeArray
let store = new PromotionClasses.Store(storeArray[i]["StoreName"], storeArray[i]["id"]);
storesInPromotionArray.push(store);
console.log(storeArray[i]["region"]);
var check = storeArray[i]["region"];
//let attr = new PromotionClasses.Attribute(storeArray[i].name, storeArray[i].type, storeArray[i].property);
//Assingattributes.push(attr);
//Create and insert a new row
let row = STORE_TABLE.insertRow(tableRowLength);
//row.contentEditable = 'true'
//The first three cells will always be the row number, store number and name
tableData["#"] = i.toString();
tableData["Number"] = storeArray[i]["storeNumber"];
tableData["Name"] = storeArray[i]["storeName"];
tableData["addressLine"] = storeArray[i]["addressLine"];
tableData["postcode"] = storeArray[i]["postcode"];
//****NESTED OBJECT PROPERTY = regionName
tableData["region"] = storeArray[i]["region"];

how can I filter an array without losing the index?

I have two really long arrays containing "picture names" and "picture files". The first one represents the actual name of the pictures, while the second one is just the file name. For example:
picturenames[0] = '0 - zero';
picturenames[1] = '1 - one';
picturenames[2] = '1 o\'clock';
...
picturefiles[0] = 'numbers-zero.jpg';
picturefiles[1] = 'numbers-one.jpg';
picturefiles[2] = 'time-1.jpg';
...
I have about 1000 items in each array in several languages (the picture files are always the same). I'm "recycling" these arrays from the previous application to save some time and avoid rewriting everything anew.
Desirable functionality: using the user's input in a textbox I want to filter the picturenames array and then show the correspondant picturefiles image.
The issue I'm facing: when I filter the picturenames array I lose the index and I can't "reach" the picture file name.
This is the code I'm using to filter the picturenames array.
var matches = picturenames.filter(function(windowValue){
if(windowValue) {
return windowValue.indexOf(textToFindLower) >= 0;
}
});
What would be the best way to do this?
UPDATE: the solution proposed by Ahmed is the best one, but for time reasons and negligible performance issues I'm just using a for loop to search trough the array, as follows:
var matchesCounter = new Array();
for (i = 0; i < picturenames.length; i++) {
if (picturenames[i].indexOf(textToFindLower) >= 0) {
matchesCounter.push(i);
}
}
console.log(matchesCounter);
for (i = 0; i < matchesCounter.length; i++) {
console.log(picturenames[i]);
console.log(picturefiles[i]);
}
Try this:
const foundIndicies = Object.keys(picturenames).filter(pictureName => {
pictureName.includes(textToFindLower)
});
// reference picturefiles[foundIndicies[0]] to get the file name
Though, it would be far nicer to have both the name and the file in a single object, like so:
const pictures = [
{
name: '0 - zero',
file: 'numbers-zero.jpg',
},
{
name: '1 - one',
file: 'numbers-one.jpg',
}
];
const foundPictures = pictures.filter(picture => picture.name.includes('zero'));
if (foundPictures[0]) console.log(foundPictures[0].file);
You can add one property index during the filtering time, then later on you can use the index.
var matches = picturenames.filter(function(windowValue, index){
if(windowValue) {
windowValue.index = index;
return windowValue.comparator(textToFindLower) >= 0;// Need to define comparator function
}
});
Later on you can access by using like follows:
picturefiles[matches[0].index]
However, the solution will work on object, not primitive type string.
If your data type is string, then you have to convert as object and put the string as a property value like name. The snippet is given below:
var picturenames = [];
var picturefiles = [];
picturenames.push({name:'0 - zero'});
picturenames.push({name:'1 - one'});
picturenames.push({name:'1 o\'clock'});
picturefiles.push({name:'numbers-zero.jpg'});
picturefiles.push({name:'numbers-one.jpg'});
picturefiles.push({name: 'time-1.jpg'});
var textToFindLower = "0";
var matches = picturenames.filter(function(windowValue, index){
if(windowValue) {
windowValue.index = index;
return windowValue.name.indexOf(textToFindLower) >= 0;
}
});
console.log(matches);

location.search.match in java script

Hi everyone I'm beginner CTF player and I have same lake with javascript and I face following problem
I couldn't understand what is the intention of following line
location.search.match(/e=(.*)/)[1]))
This is complete code
if(location.search) {
var div = document.currentScript.parentNode.appendChild(document.createElement('div'));
div.className = 'alert alert-danger';
div.role = 'alert';
div.appendChild(document.createTextNode(unescape(location.search.match(/e=(.*)/)[1])));
}
can u help me to understand it
location.search basically give you the query string part of the current URL and and match has been used to extract e parameter value from the query string with a regular expression.
As an example, if the current URL is like
https://www.example.com/?e=someone#example.com then location.search.match(/e=(.*)/)[1] will give you 'someone#example.com'.
Rest of the code basically create a div element and set extracted text as a child of it and finally append that div as a child of parent node of the currently running script tag.
Here is my working example:
This URL have multiple query parameters, such as: config=xxx & zoom=17 & lat=xxx etc...
I want to extract each query parameters one by one.
http://localhost:10/mapserver1/viewer/?config=viewer_simple1&mapserver_url=https://maps2.dcgis.dc.gov/dcgis/rest/services/Zoning/MapServer&zoom=17&lat=38.917292&long=-77.036420
This is how you do (working code):
var ___zoom = location.search.match(/zoom=([^&]*)/i)[1];
var ___lat = location.search.match(/lat=([^&]*)/i)[1];
var ___long = location.search.match(/long=([^&]*)/i)[1];
var ___basemap = location.search.match(/basemap=([^&]*)/i)[1];
var ___type = location.search.match(/type=([^&]*)/i)[1];
var ___url = location.search.match(/url=([^&]*)/i)[1];
var ___title = location.search.match(/title=([^&]*)/i)[1];
var ___opacity = location.search.match(/opacity=([^&]*)/i)[1];
//console.log(location.search.match(/zoom=([^&]*)/i)[0]); // 'zoom=17'
//console.log(location.search.match(/zoom=([^&]*)/i)[1]); // '17'
console.log(___zoom);
console.log(___lat);
console.log(___long);
console.log(___basemap);
console.log(___type);
console.log(___url);
console.log(___title);
console.log(___opacity);
This is my fully working code:
first check if parameter exist, if does, then extract it.
var ___zoom;
var ___lat;
var ___long;
var ___basemap;
var ___type;
var ___url;
var ___title;
var ___opacity;
/*
* if (value) {
*
* }
*
* will evaluate to true if value is not:
null
undefined
NaN
empty string ("")
false
0
*
*
*
*/
if ( location.search.match(/zoom=([^&]*)/i) )
{
___zoom = location.search.match(/zoom=([^&]*)/i)[1];
}
if ( location.search.match(/lat=([^&]*)/i) )
{
___lat = location.search.match(/lat=([^&]*)/i)[1];
}
if (location.search.match(/long=([^&]*)/i))
{
___long = location.search.match(/long=([^&]*)/i)[1];
}
if (location.search.match(/basemap=([^&]*)/i))
{
___basemap = location.search.match(/basemap=([^&]*)/i)[1];
}
if (location.search.match(/type=([^&]*)/i))
{
___type = location.search.match(/type=([^&]*)/i)[1];
}
if (location.search.match(/url=([^&]*)/i))
{
___url = location.search.match(/url=([^&]*)/i)[1];
}
if (location.search.match(/title=([^&]*)/i))
{
___title = location.search.match(/title=([^&]*)/i)[1];
}
if (location.search.match(/opacity=([^&]*)/i))
{
___opacity = location.search.match(/opacity=([^&]*)/i)[1];
}
//console.log(location.search.match(/zoom=([^&]*)/i)[0]); // 'zoom=17'
//console.log(location.search.match(/zoom=([^&]*)/i)[1]); // '17'
console.log(___zoom);
console.log(___lat);
console.log(___long);
console.log(___basemap);
console.log(___type);
console.log(___url);
console.log(___title);
console.log(___opacity);

Categories

Resources