Lesson 4 - Delete Random

In the previous section, we added functionality to load up a sample model. Now we can add the functionality to the next button to delete a random member.

Delete Random Member#

To delete a random member, we'll need to get all the member IDs. Then pick a random index, pull out the ID at that index and then delete the member.

Member IDs aren't always guarenteed to be in an ascending order from 1. In fact they most likely won't be.

If we were to pick a random number between 1 and the amount of members, and tried to delete the member with that ID, then it is likely to fail.

This is pretty straight forward code so let's add it to our deleteRandom function.

// Handle delete member
app.deleteRandom = function () {
// Get the current model
const model = S3D.structure.get({ api_format: true });
// Put all the member IDs into an array
const member_ids = Object.keys(model.members);
// Pick a random index - Math.random() for a
// number between 0 and 1, Math.floor() to round down
const random_index = Math.floor(Math.random() * member_ids.length);
// Get a random ID
const random_id = member_ids[random_index];
// Delete the member - the remove method will handle
// any other things that depend on this member
S3D.structure.members.remove(random_id);
// Update the view
S3D.UI.update({ redraw: true });
// Let the user know with a non-intrusive notification
SKYCIV.utils.alert.sideNotify({
title: 'Success โœ…',
body: `Member ${random_id} has been deleted.`,
time: 5000,
auto_hide: true,
theme: 'dark',
});
};

Looking good, build and test your app. You should be able to click the button until there are no more members, then click the Load Sample Model to restore the model.

important

If the App appears to lag severly, try closing the developer tools. This is a common issue with Google Chrome.

Next Section#

The App is starting to come together! In the next section, we'll look at creating a function to mimic a contruction sequence.