I have function CarFactory, which produce cars and should change color of these cars.
const warehouse = require("./warehouse");
function CarFactory(power = 10) {
this.warehouse = warehouse;
this.produceCar = (color = "red", wheels = 4, engine = false) => {
if (power < 2) {
return null
} else {
let car = { "id": warehouse.nextIdentifier, "color": color, "wheels": wheels, "engine": engine }
warehouse.createdCars.push(car);
warehouse.nextIdentifier++;
}
}
this.addEnergyPower = (value = 0) => {
power += value;
}
this.changeCarColor = (num) => {
if (power < 1) {
return null
} else {
warehouse.createdCars[num].color = 'blue'
}
}
}
module.exports = CarFactory;
But Im getting error Cannot set properties of undefined(setting 'color').
If I hardcode 0 like this to: createdCars[0] it actually works for car indexed 0.
this is warehouse file
let warehouse = {
createdCars: [],
nextIdentifier: 0
};
module.exports = warehouse;
this is where jest tries to change color
for (let i = 0; i < myFactory.warehouse.createdCars.length; i += 2) {
let car = myFactory.warehouse.createdCars[i];
if (myFactory.changeCarColor(car) !== null) {} else {
if (energyBoosts.length > 0) {
myFactory.addEnergyPower(energyBoosts.shift());
i -= 2;
} else {
break
}
}
}
From what I can tell in the line if (myFactory.changeCarColor(car) !== null) {} else{ car would be { "id": warehouse.nextIdentifier, "color": color, "wheels": wheels, "engine": engine } but what it seems like you would want is the id. So change if (myFactory.changeCarColor(car) !== null) {} else{ to if (myFactory.changeCarColor(car.id) !== null) {} else{ and see if that works.
You have this.changeCarColor = (num) but appears you want to pass a car to that and then get the id? I have no idea what this is so I then fails here:
console.log(typeof energyBoosts); with "undefined" for energyBoosts
But that is the NEXT question not the one at hand.
let warehouse = {
createdCars: [],
nextIdentifier: 0
};
function CarFactory(power = 10) {
this.warehouse = warehouse;
this.produceCar = (color = "red", wheels = 4, engine = false) => {
// console.log("here");
if (power < 2) {
return null;
} else {
let car = {
"id": warehouse.nextIdentifier,
"color": color,
"wheels": wheels,
"engine": engine
};
warehouse.createdCars.push(car);
warehouse.nextIdentifier++;
}
}
this.addEnergyPower = (value = 0) => {
power += value;
}
this.changeCarColor = (car) => {
console.log(car.color, car.id, power);
if (power < 1) {
return null;
} else {
warehouse.createdCars[car.id].color = 'blue';
}
}
}
let myFactory = new CarFactory();
//console.log(myFactory);
for (let c = 0; c < 10; c++) {
//console.log(c);
myFactory.produceCar("red", 4, false);
}
//console.log("GO!", myFactory.warehouse);
for (let i = 1; i < myFactory.warehouse.createdCars.length; i += 2) {
//console.log(i);
let car = myFactory.warehouse.createdCars[i];
console.log("Car:", car);
if (myFactory.changeCarColor(car) == null) {
console.log(typeof energyBoosts);
if (energyBoosts.length > 0) {
myFactory.addEnergyPower(energyBoosts.shift());
i -= 2;
} else {
break;
}
}
}
I made a custom game in discord. It grabs words from a list of words in the scramble-words.json file and scrambles them. Those words get put into a text chat and the user playing the game has to try and find what the actual word is. It'll delete all new messages that get sent since you started the game and keep the channel clean as long as the game is active. You have to type the word and if it's correct you get a point.
The first time the command is run the code runs fine. The second time it gives an error
UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Message with every message you send in the new game.
I've tried looking up if it had to do something with me assigning the games = {} variable as a const but I don't think that's the problem and I can't think of what else it could be.
const { words } = require('./scramble-words.json');
const Discord = require('discord.js');
/*const example = {
channelId: {
message:'message object',
stage: 'string',
counter: 'number',
currentWord: 'string',
remainingWords: ['words here'],
points: {
userId: 'points'
}
}
}*/
const games = {}
const stages = {
'STARTING': (counter, topic) => {
return `-----------------------------**Game**------------------------------\nA new "${topic} Scramble" game is starting in ${counter}s!`
},
'IN_GAME': (word, topic) => {
let scrambledWord = '';
if(topic === "Brawlhalla"){
topic = "Brawlhalla related thing"
}
scrambledWord = shuffle(word);
return `-----------------------------**Game**------------------------------\nWhat ${topic} is this?\n\n **${scrambledWord}**`
},
'ENDING': (points) => {
const sorted = Object.keys(points).sort((a, b) => {
return points[b] - points[a]
})
let embed = new Discord.MessageEmbed();
embed.setTitle('**POINTS**')
.setDescription(`**The game is now over! Here's how everyone did!**`);
var results = `\n`
var firstPlace = points[sorted[0]]
var secondPlace = null
var thirdPlace = null
var leftover = null
for(const key of sorted) {
var amount = points[key]
if(leftover){
results += `<#${key}> had ${amount} point${amount === 1 ? '' : 's'}\n`
} else if(thirdPlace) {
if(thirdPlace === amount) {
results += `:third_place: <#${key}> had ${amount} point${amount === 1 ? '' : 's'}\n`
} else {
results += `\n`
results += `<#${key}> had ${amount} point${amount === 1 ? '' : 's'}\n`
leftover = amount
}
} else if(secondPlace) {
if(secondPlace === amount) {
results += `:second_place: <#${key}> had ${amount} point${amount === 1 ? '' : 's'}\n`
} else {
results += `\n`
results += `:third_place: <#${key}> had ${amount} point${amount === 1 ? '' : 's'}\n`
thirdPlace = amount
}
} else if(firstPlace) {
if(firstPlace === amount) {
results += `:first_place: <#${key}> had ${amount} point${amount === 1 ? '' : 's'}\n`
} else {
results += `\n`
results += `:second_place: <#${key}> had ${amount} point${amount === 1 ? '' : 's'}\n`
secondPlace = amount
}
}
}
if(results === `\n`){
return embed.setTimestamp().addField(`**Nobody got points you losers**`, "🤡");
} else {
return embed.setTimestamp().addField(`**Here's how everyone did**`, results)
}
}
}
const selectWord = (game) => {
game.currentWord = game.remainingWords[Math.floor(Math.random() * game.remainingWords.length)]
const index = game.remainingWords.indexOf(game.currentWord);
game.remainingWords.splice(index, 1);
game.currentWord = game.currentWord.toLowerCase().charAt(0).toUpperCase() + game.currentWord.toLowerCase().substring(1);
}
const gameLoop = async () => {
for(const key in games) {
const game = games[key];
const { message, stage } = game;
const gameLength = 2.345
if(stage === 'STARTING') {
let string = stages[stage](game.counter, game.topic)
message.edit(string)
if(game.counter <= 0) {
game.stage = 'IN_GAME'
game.counter = 60 * gameLength
selectWord(game)
string = stages[game.stage](game.currentWord, game.topic)
message.edit(string)
}
} else if (stage === 'IN_GAME') {
if(game.counter <= 0) {
game.stage = 'ENDING'
if(game.topic === "Brawlhalla")
{
game.topic === "Brawlhalla related thing"
}
const string = `-----------------------------**Game**------------------------------\nThe last ${game.topic} was: ${game.currentWord}\n------------------------------**End**-------------------------------`
message.edit(string)
embed = stages[game.stage](game.points);
message.channel.send(embed)
await delete games[key]
await delete game
return
}
}
--game.counter
}
setTimeout(gameLoop, 1000)
}
module.exports = {
scramble(member, channel, content, guild, message, { reply }, client) {
/*if(!member.hasPermission('ADMINISTRATOR')){
reply(true, `You don't have permission to execute this command!`)
return;
}*/
if(channel.name !== "scramble-games" && channel.name !== "games"){
reply(true, `You can only do this command in a channel called "scramble-games" or "games"`);
return;
}
if(games[channel.id]){
return;
}
message.delete();
var chosenCategory= []
if(content[0]){
if(content[0].toLowerCase() === "pokemon"){
if(content[1]){
var numbers = content[1].split('')
if(!isNaN(content[1])){
for(var i = 0; i < numbers.length; i++){
if(numbers[i] === "1") {
chosenCategory = chosenCategory.concat(pokemonGeneration1)
} else if(numbers[i] === "2") {
chosenCategory = chosenCategory.concat(pokemonGeneration2)
} else if(numbers[i] === "3") {
chosenCategory = chosenCategory.concat(pokemonGeneration3)
} else if(numbers[i] === "4") {
chosenCategory = chosenCategory.concat(pokemonGeneration4)
} else if(numbers[i] === "5") {
chosenCategory = chosenCategory.concat(pokemonGeneration5)
} else if(numbers[i] === "6") {
chosenCategory = chosenCategory.concat(pokemonGeneration6)
} else if(numbers[i] === "7") {
chosenCategory = chosenCategory.concat(pokemonGeneration7)
} else if(numbers[i] === "8") {
chosenCategory = chosenCategory.concat(pokemonGeneration8)
} else {
reply(true, `The numbers you gave had a number that is higher than 8. There are only 8 gens. Try again but keep the numbers you give under 8`)
return;
}
}
} else {
reply(true, `If you want to specify gens you have to give numbers only! example: 1456 will give gens 1, 4, 5 and 6`)
return;
}
} else {
chosenCategory = chosenCategory.concat(pokemonGeneration1, pokemonGeneration2, pokemonGeneration3, pokemonGeneration4, pokemonGeneration5, pokemonGeneration6, pokemonGeneration7, pokemonGeneration8)
}
topics = "Pokemon"
} else if (content[0].toLowerCase() === "brawlhalla" || content[0].toLowerCase() === "brawl"){
chosenCategory = chosenCategory.concat(BrawlhallaLegends, BrawlhallaWeapons, BrawlhallaWords, BrawlhallaColors, BrawlhallaStances, BrawlhallaChests, BrawlhallaGamemodes)
topics = "Brawlhalla"
} else {
reply(true, `That's not a valid topic for this game!`);
return
}
} else {
chosenCategory = words
topics = "Random Word"
}
channel.send('Preparing Game...').then((message) => {
games[channel.id] = {
message,
stage: 'STARTING',
counter: 10,
remainingWords: [...chosenCategory],
points: {},
topic: topics
}
});
gameLoop(channel)
client.on('message', message => {
const { channel, content, member } = message;
const { id } = channel
const game = games[id];
if(game && game.currentWord && !member.user.bot) {
checkWord(game, member, message, content);
}
if (game && !message.author.bot) {
message.delete();
}
return;
});
}
}
function checkWord(game, member, message, content){
if(game.stage === 'IN_GAME' && content.toLowerCase() === game.currentWord.toLowerCase()) {
const owo = game.currentWord;
game.currentWord = null;
const seconds = 3;
const { points } = game
points[member.id] = points[member.id] || 0
message.reply(`You got it!\n The correct answer was: **${owo}**\n +1 point (${++points[member.id]} total)`).then(newMessage => {
newMessage.delete({
timeout: 1000 * seconds
});
});
setTimeout(() => {
if(game.stage === 'IN_GAME') {
selectWord(game)
const string = stages[game.stage](game.currentWord, game.topic)
game.message.edit(string);
}
}, 1000 * seconds);
}
}
function shuffle(word) {
var wordArray = word.split(' ');
var output = []
for(var i = 0; i < wordArray.length; i++) {
var array = wordArray[i].split('');
var currentIndex = array.length;
var temporaryValue;
var randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
output = output.concat(array)
if(!i + 1 === wordArray.length){
output.push(' ');
}
}
return output.join('');
}
Here's the json file too so you can try out the game yourself
{
"words": [
"Provincial",
"Grudge",
"Foundation",
"Carry",
"Fight",
"Belt",
"Perforate",
"Obstacle",
"Hide",
"Lesson",
"Car",
"Building",
"Mourning",
"Debut",
"Sunrise",
"Scatter",
"Clash",
"Equation",
"Performer",
"Ask",
"Butterfly",
"Medieval",
"Think",
"Minimum",
"Play",
"Sofa",
"Minority",
"Friend",
"Protect",
"Mess",
"Disability",
"Planet",
"Federation",
"Film",
"Vegetarian",
"Utter",
"Polish",
"Ankle",
"Calendar",
"Extreme",
"Student",
"Barrier",
"Motif",
"Solo",
"Toast",
"Steel",
"Speaker",
"Concede",
"Suit",
"gimping",
"Weal",
"Affords",
"Palship",
"Trefoil",
"Kirtled",
"Jaybirds",
"Shires",
"Gobbling",
"Puffery",
"Bag",
"Idoneous",
"Aerates",
"Kitchens",
"Zorils",
"Students",
"Idles",
"Howe",
"Veenas",
"Airship",
"Olefins",
"Munsters",
"Polemics",
"Lentos",
"Snog",
"Fusel",
"Giglot",
"Pinafore",
"Snowiest",
"Saxtuba",
"Division",
"Mantlet",
"Nurtures",
"Geoponic",
"Civvies",
"Trommels",
"Engraver",
"Know",
"Gummoses",
"Disbands",
"Parse",
"Donator",
"Minces",
"Lofted",
"Punters",
"Lie",
"Rune",
"Dottiest",
"Mib",
"Enwraps",
"Bizzes",
"Nitride",
"Ire",
"Bricole",
"Bigness",
"Roadeos",
"Midriffs",
"Fallers",
"Postcode",
"Sterigma",
"Duvetyne",
"Alumroot",
"Purins",
"Pricking",
"Deluders",
"Postcoup",
"Daggas",
"Rallies",
"Vocably",
"Gravida",
"Eluded",
"Dicyclic",
"Starers",
"Afflatus",
"Misbind",
"Coadmire",
"Overrule",
"Marquis",
"Pogromed",
"Dulled",
"Lantana",
"Garotte",
"Keek",
"Dhak",
"Mescals",
"Trichite",
"Theurgic",
"Cretins",
"Codicils",
"Depside",
"Cadres",
"Desium",
"Indene",
"Depicted",
"Opticist",
"Hoptoad",
"Jacking",
"Girasole",
"Wedeln",
"Pull"
]
}
Unknown message errors occur when you delete a message, then try and fetch that message, or use it in a method. I can see 2 message#delete methods in your code, and these is nearly always that cause of these errors. Go through your code and find where you are deleting the messages, and make sure you are not using anything to do with that message afterwards. The post here displays how these errors occur.
I can see one reason this error would throw, if you are iterating through the games, you use message#delete in the first game and the program runs fine, then in all of the other iterations it throws that error. This is because the message#delete is trying to delete an already deleted message (i.e. when you first deleted it in the first game).
I am getting the following error when going to the URL.
Error: could not handle the request
I can not seem to figure out why. What did I do wrong?
Here is my index.js file.
const functions = require('firebase-functions');
var request = require('request');
const admin = require('firebase-admin');
admin.initializeApp();
exports.addMessage = functions.https.onRequest(async (req, res) => {
const itemDescription = req.query.itemDescription;
const pageNumber = req.query.pageNumber;
const categoryId = req.query.categoryId;
const sortBy = req.query.sortBy;
const narrowSearch = req.query.narrowSearch;
const typeOfListing = req.query.typeOfListing;
const sellerExclusions = req.query.sellerExclusions;
const tagsExclusions = req.query.tagsExclusions;
const country = req.query.country;
const minPrice = req.query.minPrice;
const maxPrice = req.query.maxPrice;
const entriesPerPage = req.query.entriesPerPage;
const buyingFormat = req.query.buyingFormat;
let operationName = "";
let entriesPerPage2 = "";
let sortOrder = "";
let currentPage = "";
if (pageNumber !== null) {
currentPage = pageNumber;
} else {
currentPage = 1;
}
if (typeOfListing === 'active') {
operationName = "findItemsAdvanced";
entriesPerPage2 = 50;
} else {
operationName = "findCompletedItems";
if (buyingFormat === "Auction") {
entriesPerPage2 = 50;
} else {
entriesPerPage2 = 25;
}
}
let apicall = "https://URL?";
if (typeOfListing === "active") {
if (sortBy !== null) {
apicall += "&sortOrder=";
apicall += sortBy;
sortOrder = sortBy;
} else {
apicall += "&sortOrder=";
apicall += "BestMatch";
sortOrder = "BestMatch";
}
} else {
if (sortBy !== null) {
apicall += "&sortOrder=";
apicall += sortBy;
sortOrder = sortBy;
} else {
apicall += "&sortOrder=";
apicall += "EndTimeSoonest";
sortOrder = "EndTimeSoonest";
}
}
if (categoryId !== null) {
apicall += "&categoryId=";
apicall += categoryId;
}
apicall += "&paginationInput.pageNumber=";
apicall += currentPage;
apicall += "&keywords=";
apicall += itemDescription;
apicall += "&paginationInput.entriesPerPage=" + entriesPerPage2;
apicall += "&itemFilter(0).name=SoldItemsOnly&itemFilter(0).value(0)=true";
request(apicall, function (error, response, body) {
if (!error && response.statusCode === 200) {
//here put what you want to do with the request
let paginationOutput = JSON.parse(body).findCompletedItemsResponse[0].paginationOutput;
let pageNumber = null;
let totalPages = null;
let totalEntries = null;
let totalInPage = null;
for (i = 0; i < paginationOutput.length; i++) {
pageNumber = paginationOutput[i].pageNumber[0];
totalPages = paginationOutput[i].totalPages[0];
totalEntries = paginationOutput[i].totalEntries[0];
totalInPage = paginationOutput[i].entriesPerPage[0];
}
let items = JSON.parse(body).findCompletedItemsResponse[0].searchResult[0].item;
let itemId = null;
let title = null;
let categoryId = null;
let categoryName = null;
let galleryURL = null;
let link = null;
let dateEnded = null;
let watchCount = null;
let bestOfferEnabled = null;
let listingType = null;
let soldForOriginal = null;
let timeLeft = null;
let dateLeft = null;
let bidCount = null;
let shipping = null;
//TODO
let soldForBestOffer = null;
var itemArray = {
result: []
};
for (i = 0; i < items.length; i++) {
itemId = items[i].itemId[0];
title = items[i].title[0];
galleryURL = items[i].galleryURL[0];
link = items[i].viewItemURL[0];
category = items[i].primaryCategory;
for (j = 0; j < category.length; j++) {
categoryName = category[j].categoryName[0];
categoryId = category[j].categoryId[0];
}
listingInfo = items[i].listingInfo;
for (k = 0; k < listingInfo.length; k++) {
watchCount = listingInfo[k].watchCount === undefined ? "0" : listingInfo[k].watchCount[0];
bestOfferEnabled = listingInfo[k].bestOfferEnabled[0];
listingType = listingInfo[k].listingType[0];
dateLeft = listingInfo[k].endTime[0];
}
sellingStatus = items[i].sellingStatus;
for (jj = 0; jj < sellingStatus.length; jj++) {
soldForOriginal = sellingStatus[jj].convertedCurrentPrice[0].__value__;
bidCount = sellingStatus[jj].bidCount === undefined ? "0" : sellingStatus[jj].bidCount[0];
timeLeft = sellingStatus[jj].timeLeft === undefined ? "-" : sellingStatus[jj].timeLeft[0];
}
shippingInfo = items[i].shippingInfo;
for (ii = 0; ii < shippingInfo.length; ii++) {
shipping = shippingInfo[ii].shippingServiceCost === undefined ? "0.0" : shippingInfo[ii].shippingServiceCost[0];
shippingType = shippingInfo[ii].shippingType[0];
if (shipping === "0.0") {
shipping = "0.00"
}
if (shippingType === 'Calculated') {
shipping = "TBD";
} else {
if (shipping === '0.00') {
shipping = "FREE";
}
}
}
itemArray.result.push({
"itemId": itemId,
"title": title,
"galleryURL": galleryURL,
"link": link,
"categoryName": categoryName,
"categoryId": categoryId,
"bidCount": bidCount,
"dateEnded": dateLeft,
"watchCount": watchCount,
"bestOfferEnabled": bestOfferEnabled,
"listingType": listingType,
"timeLeft": timeLeft,
"soldForOriginal": soldForOriginal
});
}
res.json({
ack: "success",
message: "results found",
currentPage: pageNumber,
totalPages: totalPages,
totalEntries: totalEntries,
totalInPage: totalInPage,
results: itemArray.result,
searchResult: JSON.parse(body).findCompletedItemsResponse[0].searchResult[0].item
});
} else {
res.json({
error: "didnt work"
});
}
})
});
In Cloud Functions you need to manage asynchronous method calls via Promises. request supports callback interfaces natively but does not return a promise.
You should use another library, like axios, along the following lines:
exports.addMessage = functions.https.onRequest(async (req, res) => {
try {
// ...
let apicall = "https://URL?";
// ...
apicall += "&itemFilter(0).name=SoldItemsOnly&itemFilter(0).value(0)=true";
const response = await axios.get(apicall);
// handle success
// ...
res.json({..});
} catch (error) {
res.status(500).send({ 'error': error });
}
});
Note that you probably need to be on the "Blaze" pricing plan.
As a matter of fact, the free "Spark" plan "allows outbound network requests only to Google-owned services". See https://firebase.google.com/pricing/ (hover your mouse on the question mark situated after the "Cloud Functions" title)
Also note that request is deprecated.
I understand that this question has been asked before but none of the previous answers have helped me.
This is my function:
function execute() {
console.log('here')
const q = document.getElementById('myinput').value
return gapi.client.youtube.search.list({
"part": "snippet",
"order": "viewCount",
"q": q,
"type": "video",
"videoDefinition": "high",
"maxResults": 10
})
.then(function(response) {
console.log("Response", response);
const z = response.result.items
console.log("x", z)
return(z.map(vid => {
console.log("vid", vid)
const date = document.createElement('div')
const title = document.createElement('h2')
const video = document.createElement('iFrame')
date.textContent = vid.snippet.publishedAt
title.textContent = vid.snippet.title
const x = document.getElementById('results')
console.log(date)
x.append(date)
x.append(title)
x.append(video)
const w = document.getElementById('date')
const v = document.getElementById('view')
function sorting(){
const items = vid.childNodes;
const itemsArr = [];
for (var i in items) {
if(items[i].nodeType == 1){
itemsArr.push(items[i])
}
}
itemsArr.sort(function(a,b){
return a.innerHTML === b.innerHTML
? 0
: (a.innerHTML > b.innerHTML ? 1 : -1);
});
for (i = 0; i < itemsArr.length; ++i){
w.appendChild(itemsArr[i])
}
}
return(x)
}))
},
function(err) { console.error("Execute error", err); });
}
I want to trigger that sorting function on my onclick: <option onclick="execute().sorting()"id = "date">Date</option>
If you know how I can call it or even if you know a better way of sorting videos by date and view count, please leave a comment or answer. Any help is appreciated.
OH! I should add, this has to be done in pure vanilla javascript.
Edit
You asked for the HTML:
<button onclick="execute()">Search</button>
<h3>Sort:</h3>
<select>
<option onclick="execute.b()"id="view" value="viewCount">View Count</option>
<option onclick="execute().sorting()"id = "date">Date</option>
</select>
You can create a constructor function with a nested function sorting scoped to this object when initiated, and then initiate it in js i.e.:
function Execute() {
this.search = function(){
console.log('here')
const q = document.getElementById('myinput').value
return gapi.client.youtube.search.list({
"part": "snippet",
"order": "viewCount",
"q": q,
"type": "video",
"videoDefinition": "high",
"maxResults": 10
})
.then(function(response) {
console.log("Response", response);
const z = response.result.items
console.log("x", z)
return (z.map(vid => {
console.log("vid", vid)
const date = document.createElement('div')
const title = document.createElement('h2')
const video = document.createElement('iFrame')
date.textContent = vid.snippet.publishedAt
title.textContent = vid.snippet.title
const x = document.getElementById('results')
console.log(date)
x.append(date)
x.append(title)
x.append(video)
const w = document.getElementById('date')
const v = document.getElementById('view')
this.sorting();
return (x)
}))
},
function(err) {
console.error("Execute error", err);
});
};
this.sorting = function() {
const items = vid.childNodes;
const itemsArr = [];
for (var i in items) {
if (items[i].nodeType == 1) {
itemsArr.push(items[i])
}
}
itemsArr.sort(function(a, b) {
return a.innerHTML === b.innerHTML ?
0 :
(a.innerHTML > b.innerHTML ? 1 : -1);
});
for (i = 0; i < itemsArr.length; ++i) {
w.appendChild(itemsArr[i])
}
};
}
Then create an instance when the whole page loads:
var executeInstance;
window.onload = function(event){
executeInstance = new Execute();
};
And in the HTML then call the instance (not sure what function b is, not present in initial example):
<button onclick="executeInstance.search()">Search</button>
<h3>Sort:</h3>
<select>
<option onclick="executeInstance.b()"id="view" value="viewCount">View Count</option>
<option onclick="executeInstance.sorting()"id = "date">Date</option>
</select>
More on Object Constructor:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor
I am getting an error TypeError: animalData.slice is not a function
inside this method handleskyChange at the below line
let activeList = animalData.slice(skySlicestartNumber, skySliceEndNumber).map(data => {
I debugged and put console I was getting the values in animalData.
so I put an if condition for undefined and empty
but I am getting same error.
can you tell me how to fix it.
providing my code snippet below.
handleskyChange = (skyNumber, skyItemsCount = 0) => {
// console.log('handleChange ->', skyNumber);
// console.log('skyItemsCount ->', skyItemsCount);
skyNumber = skyNumber
? skyNumber.currentsky
? skyNumber.currentsky
: skyNumber
: 0;
let itemsCount = Number(
skyItemsCount === 0 ? this.state.skyItemsCount : skyItemsCount
);
let animalData = this.props.animalData.hasOwnProperty(
'content'
)
? this.props.animalData.content
: this.props.animalData;
let animalDataCount = this.props.animalData.hasOwnProperty(
'totalCount'
)
? this.props.animalData.totalCount
: 0;
this.setState({
animalDataLength: animalDataCount,
});
let skySlicestartNumber = (skyNumber - 1) * itemsCount;
let skySliceEndNumber = skySlicestartNumber + itemsCount;
console.log("animalData--->", animalData);
if (animalData != undefined && animalData != '') {
console.log("inside if animalData--->", animalData);
let activeList = animalData.slice(skySlicestartNumber, skySliceEndNumber).map(data => {
data.expanded = false;
return data;
});
this.setState({
activeList: activeList,
});
}
this.setState({ skyNumber: skyNumber, skyItemsCount: itemsCount });
this.setState({ activesky: skyNumber });
if (
(Object.keys(this.props.rankSearch).length > 0 &&
this.state.skyNumber != skyNumber) ||
this.state.skyItemsCount != itemsCount
) {
const house = {};
house['skyNumber'] = skyNumber;
house['skySize'] = itemsCount;
{
this.props.callContentCentralResults(
this.props.rankSearch,
'ranks',
house
);
}
}
};
animalData output
{
"uniqueKey": 01222222222222222,
"pin": true,
"value": "{\"expanded\":true,\"value\":0,\"showpin\":true,\"groupCheckBoxValues\":[{\"label\":\" \\n | "activeList\":[],\"skyItemsCount\":78,\"list\":[],\"skyNumber\":1,\"individualPaginateCheckboxes\":[],\"totalRecords\":6}",
"skyNumber": 1,
"skyItemsCount": 78
}
slice is not working on object but only on arrays, to access keys try
Object.keys(animalData).slice(...)