Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
camoseven
Dec 30, 2005

RODOLPHONE RINGIN'

echinopsis posted:

next step is figuring out date()

If you need to do anything complicated I highly recommend using a library instead of trying to deal with the native Date interface directly. We use Day.js at work but there's a bunch of options

Adbot
ADBOT LOVES YOU

Video Nasty
Jun 17, 2003

camoseven posted:

If you need to do anything complicated I highly recommend using a library instead of trying to deal with the native Date interface directly. We use Day.js at work but there's a bunch of options

Moment.js is my go-to library when dealing with date\time objects if I can use it (sometimes I can't :gonk: )

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'

Video Nasty posted:

Moment.js is my go-to library when dealing with date\time objects if I can use it (sometimes I can't :gonk: )

I'm sorry you had to find out this way but here's a note from the Moment devs:

Moment.js is a legacy project, now in maintenance mode. In most cases, you should choose a different library.

Video Nasty
Jun 17, 2003


Well there's egg on my face! I'll have to look into Day.js and see what's it all about.

e: oh this is legit. I'm definitely using this from now on!

echinopsis
Apr 13, 2004

by Fluffdaddy
day.js it is then

given how important it is to my game, i’m happy to use a library if it makes my life work

echinopsis
Apr 13, 2004

by Fluffdaddy
this day.js is very good, but I need relative times, which it can't do without a plugin, which requires "require" lol, which is a node thing, and probably needs a plugin to make it work in browser.

I might go with date-fns since it's not minimalist and hopefully means one package will be enough

echinopsis
Apr 13, 2004

by Fluffdaddy

echinopsis posted:

this day.js is very good, but I need relative times, which it can't do without a plugin, which requires "require" lol, which is a node thing, and probably needs a plugin to make it work in browser.

I might go with date-fns since it's not minimalist and hopefully means one package will be enough

poo poo this is driving me crazy.

is it normal that everything assumes you're running node?

at least the dayjs was straightforward, it worked well until I couldn't figure out how to include plugins

anyway, it's a slow road trying to get something as basic as datetime working it seems.

e:

have worked out half of how to import plugins with dayjs into the browser without required node or whatever. thanks for reading

echinopsis fucked around with this message at 02:21 on Jun 14, 2022

Toast Museum
Dec 3, 2005

30% Iron Chef
A site I use for work makes heavy use of popups produced by inline onclick functions. The URL for the popup is one of the parameters of these functions. For a given onclick event, is there a way to reflect on the URL argument that's been given to the function? I'd like to write a userscript to make the site less popup-happy, and I'm really hoping there's an alternative to parsing the function invocations as strings.

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'

echinopsis posted:

poo poo this is driving me crazy.

is it normal that everything assumes you're running node?

at least the dayjs was straightforward, it worked well until I couldn't figure out how to include plugins

anyway, it's a slow road trying to get something as basic as datetime working it seems.

You usually want to use import for front end apps, though you can load scripts directly as indicated by the DayJS docs.

echinopsis
Apr 13, 2004

by Fluffdaddy

camoseven posted:

You usually want to use import for front end apps, though you can load scripts directly as indicated by the DayJS docs.

I'm trying that final method, and the tricky part seems to be the dayjs.extend();

I don't seem to be able to paste source stuff into this but basically I
script src https://unpkg.com/dayjs@1.11.3/dayjs.min.js
script src https://unpkg.com/dayjs@1.11.3/plugins/relativetime.min.js

and then dayjs.extend(relativetime)

now that plain didn't work, so I tried extend(window.relativetime)

and that seems to work.. except it seems to be finding a problem
code:
Uncaught TypeError: Cannot read properties of undefined (reading '$i')
    at w.extend (dayjs.min.js:1:6457)
    at index.html:25:13
which kind of seems like it's saying the scripts I am referencing have errors. although I am sure it's something I am doing wrong.




e: but I finally got it working, I copied the scripts into my own folder and discovered I needed to extend day.js with dayjs_plugin_relativeTime not something else. which I only found by looking thru the relativetime.js

maybe I am dumb but I am not sure why that's not clear on the docs that you need to reference it like that, copying and pasting their stuff just didn't work.

NOW on with the show

echinopsis fucked around with this message at 02:56 on Jun 14, 2022

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'

echinopsis posted:

I'm trying that final method, and the tricky part seems to be the dayjs.extend();

I don't seem to be able to paste source stuff into this but basically I
script src https://unpkg.com/dayjs@1.11.3/dayjs.min.js
script src https://unpkg.com/dayjs@1.11.3/plugins/relativetime.min.js

and then dayjs.extend(relativetime)

now that plain didn't work, so I tried extend(window.relativetime)

and that seems to work.. except it seems to be finding a problem
code:
Uncaught TypeError: Cannot read properties of undefined (reading '$i')
    at w.extend (dayjs.min.js:1:6457)
    at index.html:25:13
which kind of seems like it's saying the scripts I am referencing have errors. although I am sure it's something I am doing wrong.

Capitalization matters for the extend, it's relativeTime

echinopsis
Apr 13, 2004

by Fluffdaddy

camoseven posted:

Capitalization matters for the extend, it's relativeTime

this didn't work, and neither did window.relativeTime, wasn't until I did the "dayjs_plugin_relativeTime" that it worked

thanks though. slowly hacking my way thru this

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself

Video Nasty posted:

Moment.js is my go-to library when dealing with date\time objects if I can use it (sometimes I can't :gonk: )

i did a live coding interview recently where I had to implement a calendar app from scratch with no libraries.

i haven't used native JS dates in forever. it was some kind of sadistic bullshit.

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

teen phone cutie posted:

i did a live coding interview recently where I had to implement a calendar app from scratch with no libraries.

i haven't used native JS dates in forever. it was some kind of sadistic bullshit.

yeah i'd just bounce. that is sadistic.

i've had to fix software used for pediatric oncology that would calculate the age of the infant incorrectly because the children were still at the age where # of months matters, and they tried to do date diffing in native js. i deleted that page of nonsense and made it use a single call in moment.js (this was back when moment was still recommended for use in new projects etc.)

i am somewhat reluctant to go "guess what, we shouldn't use moment.js anymore!" to the people who work on that project now. I don't think it'll be well received.

echinopsis
Apr 13, 2004

by Fluffdaddy
once I got over being mad at the less than obvious (for me) way to add the plugins to dayjs and got my head around it, it all ended up running smoothly.


thanks to everyone for their patience with me lol. the games called https://crimecommitter.com and no it’s not very good but at least it kind of works without being buggy and next step is flesh out the crime content

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice
I use Luxon for dates, and it is very nice and does just about anything one would need, and it's immutable, which every date library should be.

worms butthole guy
Jan 29, 2021

by Fluffdaddy
Hey goons simple question. It's been a while since I messed around with NodeJS and PUG.

How do I wait for a DB call using mongoose and then render the page? I'm trying to experiment with OAuth and I need to make a call to get user Information and I want to display it to test it. Here is what I have:

code:


// Lookup DB
const LookUpDB =  async (accountID) => {
  Account.findOne({accountId : accountID}, (e, account)=>{
      if (e){
        console.log(e);
      }

      console.log('Account info: ' + account);

      return account;
  });
}

/* GET home page. */
router.get('/', async function(req, res, next) {

  try{
    const accountInfo = await LookUpDB(1);

    res.render('index', { title: 'Foxtrot Tango', loggedIn, accountInfo });
  }
  catch(e){
    next(e);
  }

});
The console log in LookUpDB works, but Pug thinks there's nothing in accountInfo when I console log it. I'm guessing it has to do with Async and Await?

Thanks goons

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'

worms butthole guy posted:

Hey goons simple question. It's been a while since I messed around with NodeJS and PUG.

How do I wait for a DB call using mongoose and then render the page? I'm trying to experiment with OAuth and I need to make a call to get user Information and I want to display it to test it. Here is what I have:

code:


// Lookup DB
const LookUpDB =  async (accountID) => {
  Account.findOne({accountId : accountID}, (e, account)=>{
      if (e){
        console.log(e);
      }

      console.log('Account info: ' + account);

      return account;
  });
}

/* GET home page. */
router.get('/', async function(req, res, next) {

  try{
    const accountInfo = await LookUpDB(1);

    res.render('index', { title: 'Foxtrot Tango', loggedIn, accountInfo });
  }
  catch(e){
    next(e);
  }

});
The console log in LookUpDB works, but Pug thinks there's nothing in accountInfo when I console log it. I'm guessing it has to do with Async and Await?

Thanks goons

Right now that `return account` is returning the value to the outer function (LookUpDB), but LookUpDB is not returning anything so when you invoke it you just get undefined. findOne is already an async function, so you don't need to wrap it like you're doing.

edit: i should say I'm pretty sure it's already async. I don't use mongoose but that's what skimming the docs leads me to believe

worms butthole guy
Jan 29, 2021

by Fluffdaddy

camoseven posted:

Right now that `return account` is returning the value to the outer function (LookUpDB), but LookUpDB is not returning anything so when you invoke it you just get undefined. findOne is already an async function, so you don't need to wrap it like you're doing.

edit: i should say I'm pretty sure it's already async. I don't use mongoose but that's what skimming the docs leads me to believe

That makes sense!

I reconfigured it into:

code:
const LookUpDB = (accountID) => {
  const accountInfo = Account.findOne({accountId : accountID}, (e, account)=>{
      if (e){
        console.log(e);
      }

      console.log('Account info: ' + account);

      return account;
  });

  return accountInfo;
}
Now i'm dealing with Query already executed, but I think Ill have a easier time debugging that error. Thanks!

worms butthole guy fucked around with this message at 19:58 on Jun 15, 2022

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'
No problem. I will say that your abbreviation of "error" to "e" is triggering me lol. In my experience "e" is used in event handlers as the event object, whereas an error check would refer to "err" or "error"

lifg
Dec 4, 2000
<this tag left blank>
Muldoon
Committing package-lock.json to the repo. Good idea or bad idea?

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself

lifg posted:

Committing package-lock.json to the repo. Good idea or bad idea?

requirement. that's the file that locks down the version numbers so that when your coworker pulls down the project and installs the dependencies, they'll be using the same exact dependency versions as you

lifg
Dec 4, 2000
<this tag left blank>
Muldoon

teen phone cutie posted:

requirement. that's the file that locks down the version numbers so that when your coworker pulls down the project and installs the dependencies, they'll be using the same exact dependency versions as you

And it can’t be recreated exactly given the version numbers in package.json?

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself

lifg posted:

And it can’t be recreated exactly given the version numbers in package.json?

typically when you install a package, a version number gets written to package.json like "^1.0.0" which means "install v1.0.0 at a minimum, but also you can install something greater if it exists."

so the version you install might be unexpected.

removing the up carrot will pin the version number but it's usually best practice to just leave the carrot and let the lock file do what it was meant to.

teen phone cutie fucked around with this message at 04:49 on Jun 16, 2022

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

lifg posted:

And it can’t be recreated exactly given the version numbers in package.json?

When you try to lock it down to a specific version for every package you end up with a package json with 50 different locked dependencies, which have dependencies so 500 total. Because the company you work for is obsessed with adding them. All of which are wildly out of date and eventually you need to update them. Why? Because you want to update Node, you're on some version of Node that doesn't support lambdas or async or something.

Unfortunately none of the dependencies have seen even incremental updates all this time.

So you update a key one and then three others fail. So you update one of them and 4 others fail so you try to update those and 20 others fail. You're in Hell. Update everything, then go through every single one of them trying to figure out what's changed. Spend a month on it.

Find out that many dependencies need a full version point or two update. Look through all of their respective changelogs if they even exist. Look through the code base otherwise. And there are still people on this forum who say "I don't care if there's dependencies I will never care about what's in my node_modules dir."

Npm is a nightmare if you've worked in this industry.

Nolgthorn fucked around with this message at 00:00 on Jun 16, 2022

Ima Computer
Oct 28, 2007

Stop all the downloading!

Help computer.
https://www.youtube.com/watch?v=Uo3cL4nrGOk

quote:

My job is to keep our code running while other packages are changing theirs.

echinopsis
Apr 13, 2004

by Fluffdaddy
Hi, I've run into some confusing activity here.

so

JavaScript code:
function generateAccumulatedDataText(buttonIndex) {
    accumDataText = "<br><br>YOU'VE COMMITTED THIS CRIME " +
        setOfAccumlatedData[buttonIndex].numberTimesCommitted +
        " TIMES<br>" +
        "AND EARNED<br>" +
        setOfCrime[buttonIndex].notoEarned *
        setOfAccumlatedData[buttonIndex].numberTimesCommitted +
        " NOTORIETY<br>" +
        setOfCrime[buttonIndex].moneyEarned *
        setOfAccumlatedData[buttonIndex].numberTimesCommitted +
        " $<BR>AND SPENT " +
        dayjs
        .duration(
            setOfCrime[buttonIndex].timeToCompleteInMilliseconds *
            setOfAccumlatedData[buttonIndex].numberTimesCommitted,
            "millisecond"
        )
        .format("DD HH:mm:ss") +
        " DOING SO";
}
I had this very long string building thing in another function and it was working fine, but I was going to have to use it in two places so I pulled it out into it's own function, and now it does this
https://twitter.com/_crimecommitter/status/1537339000884953088?s=20&t=ZUgBbHaQLHz6uzWthzrg7A

at first the function returned the string and it had the same problem. then I thought I'd just abuse global variables so I do it that way, but the same problem.

In the console, if I access the variable it returns the correct string.

It wouldn't be so weird except it works if I just put that code into the original function.




e: fixing that next problem fixed this lol

echinopsis fucked around with this message at 09:52 on Jun 16, 2022

echinopsis
Apr 13, 2004

by Fluffdaddy
Also this also confuses me


ok so setOfAccumulatedData is an array of a function, which has the variable numberTimesCommitted in each function. I am using the function basically as a struct since javascript doesn't have structs
BUT

JavaScript code:
   setOfAccumlatedData[buttonIndex].numberTimesCommitted += 1;
appears to increment the numberTimeCommitted in each element of the array and not just the one defined by buttonIndex

I can't work out how the heck

e: I create the function like this
JavaScript code:
// struct for accumulated data (I expect to add more as time goes on)
function structOfAccumulatedData(numberTimesCommitted) {
    this.numberTimesCommitted = numberTimesCommitted;
}
and initialise it like this
code:
// initialise the accumulated data array
var setOfAccumlatedData = new Array(setOfCrime.length).fill(
    new structOfAccumulatedData(0)
);
according to the console log, the setOfAccumulatedData contains a bunch of structOfAccumulatedData

it's like there is only one numberTimeCommitted variable rather than one per each in the array



e2: I have fixed it, but only by expanding my initialisation method, and just expanded it, but it feels messy, and I'm sure the problem is me misunderstanding how to automatically make an array of functions


e3: I just expanded it to this:
JavaScript code:
// initialise the accumulated data array
var setOfAccumlatedData = new Array(setOfCrime.length);
// use a for loop to fill them
for (let initAccumDataIndex = 0; initAccumDataIndex < setOfCrime.length; initAccumDataIndex++) {
    setOfAccumlatedData[initAccumDataIndex] = new structOfAccumulatedData(0);
}
and it now works. kind of feels gross to have had to expanded it to a for loop but whelp

echinopsis fucked around with this message at 09:38 on Jun 16, 2022

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
This code:
code:
// initialise the accumulated data array
var setOfAccumlatedData = new Array(setOfCrime.length).fill(
    new structOfAccumulatedData(0)
);
creates one new object, and then makes every slot of the array point to that one single object.

Your fixed code creates a different object for every array slot.

For reference though one the things people find really handy about JS is how easy it is to make new "plain old data" objects:

code:
var foo = {
  key: "value"
}
You'll probably find this more convenient than making a new Function object just so you can attach extra values to it.

You can also use array.push instead of explicitly iterating over the array indices:

code:
var things = [];
for (var i = 0; i < numberOfThings; i++) {
  things.push(makeThing(i));
}

echinopsis
Apr 13, 2004

by Fluffdaddy

Jabor posted:

This code:
code:
// initialise the accumulated data array
var setOfAccumlatedData = new Array(setOfCrime.length).fill(
    new structOfAccumulatedData(0)
);
creates one new object, and then makes every slot of the array point to that one single object.

Your fixed code creates a different object for every array slot.

For reference though one the things people find really handy about JS is how easy it is to make new "plain old data" objects:

code:
var foo = {
  key: "value"
}
You'll probably find this more convenient than making a new Function object just so you can attach extra values to it.

You can also use array.push instead of explicitly iterating over the array indices:

code:
var things = [];
for (var i = 0; i < numberOfThings; i++) {
  things.push(makeThing(i));
}
hmm I'm too deep into my code to change it now, but does that method allow you to basically create a struct?

this is what I am doing :

code:
function structOfCrimes(
  buttonid,
  name,
  cost,
  requiredNoto,
  moneyEarned,
  notoEarned,
  timeToCompleteInSeconds,
  timeToCompleteInHours,
  datetimeCrimeStarted,
  datetimeCrimeWillEnd
) {
  this.buttonid = buttonid;
  this.name = name;
  this.cost = cost;
  this.requiredNoto = requiredNoto;
  this.moneyEarned = moneyEarned;
  this.notoEarned = notoEarned;
  this.timeToCompleteInSeconds = timeToCompleteInSeconds;
  this.timeToCompleteInHours = timeToCompleteInHours;
  this.timeToCompleteInMilliseconds = timeToCompleteInHours * 60 * 60 * 1000 + timeToCompleteInSeconds * 1000;
  // state refers to where the crime is at
  // 0 = ready to run
  // 1 = running
  // 2 = completed but haven't collected resources
  // 3 = unavailable (need more noto)
  this.datetimeCrimeStarted = 0;

  this.datetimeCrimeWillEnd = 0;
}

// this creates an array "setOfCrime" that contains different crimes
var setOfCrime = [
  new structOfCrimes("loit", "Loitering", 0, 0, 0, 2, 12, 0, 0, 0),
  new structOfCrimes("skate", "Skateboarding", 0, 10, 0, 5, 45, 0, 0, 0),
  new structOfCrimes("litt", "Littering", 0, 2, 0, 1, 4, 0, 0, 0),
  new structOfCrimes("watch", "Selling Counterfeit Watches", 0, 20, 5, 2, 60, 0, 0, 0),
  new structOfCrimes("baby", "Candy from a Baby", 0, 12, 0, 3, 28, 0, 0, 0),
  new structOfCrimes("jorts", "Wearing Jorts", 5, 17, 0, -5, 60, 0, 0, 0),
];
creating a function that acts as a struct, and then creating an array of that struct to act as one large data hoard

my "background" if you will is unreal engine and so I work things how I worked them there



Jabor posted:

This code:
code:
// initialise the accumulated data array
var setOfAccumlatedData = new Array(setOfCrime.length).fill(
    new structOfAccumulatedData(0)
);
creates one new object, and then makes every slot of the array point to that one single object.

yeah I suspected something like this was happening

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
You could totally do something like:

code:
var setOfCrime = [
  {
    buttonid: "loit",
    name: "Loitering",
    notoEarned: 2,
    timeRequired: 12
  },
  {
    buttonid: "skate",
    name: "Skateboarding",
    requiredNoto: 10,
    notoEarned: 5,
    timeRequired: 45
  },
  // etc.
]
The way you've got it also works though.

echinopsis
Apr 13, 2004

by Fluffdaddy
O yep I see

I actually have a CSV file with that data in it that I use a hacky python script to that outputs to a file that I copy and paste into my code, so that over time it's easy for me to add more crimes without fiddling in the code.

I could probably work out how to have a separate data file lol.

camoseven
Dec 30, 2005

RODOLPHONE RINGIN'
I'm enjoying following your progress and am looking forward to Committing some Crimes

echinopsis
Apr 13, 2004

by Fluffdaddy
Thankyou. I’ve enjoyed the whole process and even come to like javascript lol. I’m certainly proud of how far I’ve come, and I thought I was going to have to spend a day working out cookies and I managed to knock it out in a few hours, the best part being the section where I combine an array into a single cookie (by joining them into one string with “;”) and then later pull them apart with split, I managed to write all at once and it all worked.

I know I’m getting better when I can write entire sections that work first try.

I did have other problems with cookies though and it didn’t help that I couldn’t debug them without uploading to the website but managed to get it working.


The game is highly functional now, and just needs me to put some decent time into making a decent list of crimes to do. which weirdly I fine quite difficult. BUT no excuses, and I have 6 more days off due to covid so I should be able to get it done.

And there is definite work on the css left to be done lol. while a small amount of jankiness contributes to its aesthetic, I defo need to make it work on more than just full sized desktop screens. and link to a merch page or course. lol

With cookies now working, it’s feasible to have crimes that take days and weeks to complete* and also should be able to update it and add to it without breaking it so in theory there’s maybe interesting things for people to come back to

* I don’t use any kind of countdown per se, I just encore the end datetime the moment you hit go on any particular crime, so it doesn’t matter if you close the browser, and when you come back it’ll recalc their state so you’ll come back to completed crimes ready to collect


I’m quite “excited” about making some other websites though.

A major step would be logins, and I understand using something like django would take a lot of the hard
work out, except at the moment it’s 100% client side and hosted at github and so I am sure if I took the next big step of having logins it’d mean quite a significant change. although it would allow me to email people to tell them they’ve got uncollected crimes. ugh there is always scope for adding features lol



Thanks to everyone in this thread who helped, you’ve all been helping and the fact you were so willing to help also meant so much.

Osmosisch
Sep 9, 2007

I shall make everyone look like me! Then when they trick each other, they will say "oh that Coyote, he is the smartest one, he can even trick the great Coyote."



Grimey Drawer
Agreeing that following your progress has been fun!

You could look into hosting on glitch, they have a lot of features for free pet projects like this one, up to and including dbs/logins as I understand it.

Time to rack up some more notoriety.

echinopsis
Apr 13, 2004

by Fluffdaddy

Osmosisch posted:

Agreeing that following your progress has been fun!

You could look into hosting on glitch, they have a lot of features for free pet projects like this one, up to and including dbs/logins as I understand it.

Time to rack up some more notoriety.

Thanks for the tip, I'll look into it :)

tbh I don't mind paying some money either. I've offered a local comedian $100 for an hour or so work to write up some paragraphs for the crimes, to provide incentive to play deeper and deeper

echinopsis
Apr 13, 2004

by Fluffdaddy
seeing as I've hired a person to write me up some descriptions etc, I suppose it would be wise to store these in a data file,

now I've been looking around, is JSON the best format to use for this? will it have trouble with commas etc? (spose I can always encode those somehow)

because it makes sense to me to store this data, which will be large character wise, in it's own file and keep the javascript file clean.

and I could store all that information that I declare into my function in the data file, and if it's json then it's designed from the ground up to be readily read by javascript, right?

The other day I was thinking about storing it in csv, but then I'd need a special way to convert out of csv, but if it's json then it's kind of ready to go? am I understanding that correctly? I could easily make a for loop that cycled through all the json entries and fill up my setOfCrime array? or as I am writing this, perhaps even skip that step and directly reference the json file where and when I need to instead of an intermediate array of structs?

Initially my setOfCrime array was carrying mutable gamestate data but I've moved that into it's own array now so the setOfCrime array is read-only anyway, could I entirely skip that step and read from the json where and when I need it? Or would it still be wise to have that intermediate variable hanging around in memory or not for performance reasons*?



*because I tell you what, my code is NOT efficient lol, I know I do a lot of inefficient refreshes for the sake of making it easy to code and think about. every single page redraw (however many times per second that is) checks every single crime to see if it's finished, updates the time on it, refreshes the top banner, the current time.
When I have more crimes to do, spose it might be prudent to reduce this to every half second or so. seeing as it's not my cpu cycles I'm using doing this lol.

gbut
Mar 28, 2008

😤I put the UN🇺🇳 in 🎊FUN🎉


Unless you have a really MASSIVE amount of data, don't worry about the memory footprint in contemporary hardware, especially if the data is hand-compiled, it doesn't sound like it should be relevant.

Yes, you can store it in JSON, which would make it trivial to use in your JS code, considering that JSON is valid JS. It stands for JavaScript Object Notation, and is basically just an "object" (a basis JS data structure) on its own, in a file/server response/whatever.

For characters that need to be escaped in JSON, it's basically the quotes (\") and newlines (\n), but I'm probably missing some in this short list. Commas are definitely not a problem.

e: missed some parts of the question:

You don't need an intermediate variable. You could very easily either define your initial state as an array or an object and use it in your code as-is. You could define that variable in a different file, if you want to separate your data from you code, but how to do that depends on where your code is executing. In any case, look into modules (there are different kinds) but seem to be settling on ES6 ones lately.

gbut fucked around with this message at 00:25 on Jun 17, 2022

echinopsis
Apr 13, 2004

by Fluffdaddy
Thankyou, that certainly settles it for me that I'll use a JSON file to store all this data.

I'll probably keen defining the array in my main code, just directly reference the data in the JSON file, and try to format the data in the JSON file exactly as I will be using it in my code.

Adbot
ADBOT LOVES YOU

echinopsis
Apr 13, 2004

by Fluffdaddy
can I ask a question about JSON

I'm trying to hold all my crime data (read only stuff) in a JSON file, and I am unsure of how to have the layout.

my goal would be to access it like
code:
JSONFile.crimes[12].name
here's what I have with thr JSON file so far
code:
{
  "crimes": [
    {
      "buttonid": "",
      "name": "",
      "cost": 0,
      "requiredNoto": 0,
      "moneyEarned": 0,
      "notoEarned": 0,
      "timeToCompleteInSeconds": 0,
      "timeToCompleteInHours": 0
    },
    {
      "do more of the same"
    }
  ]
}

{
    "spiels":[
        {
            "buttonid":"some great words"
        },
        {
          do more of the same
        }
        
    ]
}
one large array for the crime data and a second large array that holds just some text/spiel/praragraph about the crimes


am I heading in the right direction?

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply