This is an old revision of the document!


p5js week 08

(photo from https://www.foodnetwork.com/how-to/packages/food-network-essentials/tips-on-toast)

Now you're able to represent toast in more and more sophisticated ways. You can put that toast into arrays and then process it with forEach and map. You can draw your toast in p5js. You can draw lots of other stuff as well! You've made at least two drawings, and probably a lot more. Now let's learn one more way to process arrays called filter, and then let's use that and everything else we've learned to make a new drawing.

Here's a list of things to try this week:

  1. making your own class
  2. filter
  3. combining methods for arrays
  4. p5js: using filter to draw
  5. p5js: drawing with your own class

Can you make a drawing that does the following?

  1. draw an animal, plant, or a complicated shape from your imagination
  2. there should be many different versions of it, like different sizes and different colors
  3. make a class to draw it
  4. use buildArray to fill an array of objects from your class; try to make 100 or more!
  5. use filter to change your drawing in some way

Before we start drawing, let's learn some more about JavaScript. By the end of the next section, we'll have made a toast chef simulator! We'll use JavaScript to simulate chefs making toast, then we'll write some functions to score them to find out which toast chefs pass our test!

(photo from https://www.maangchi.com/wp-content/uploads/2020/04/street-toast-insta-scaled.jpg)

So that we can do new things with our code-toast, we want to learn the filter method for arrays. Then we'll practice using it by combining it with our other useful functions, forEach, and map to make our toast chef simulator.

  1. filter
  2. combining methods for arrays

We can use forEach as an alternative to a for-loop to do a lot of things with arrays. We can use map to do a calculation based on each item in an array and return a new array. When we use map, we will get an array which is the same length as the array that we call map on. Sometimes, we just want some of the items in an array. In that case, we use another method for arrays called filter.

Filter lets us choose some of the items from an array based on a function that returns a boolean; finally it returns a new array. We can test each item in an array using this function; if it returns true, it will include the item in the new array. If that function returns false, the item will be excluded or filtered out. Try this code:

let allTheToast = ["regular toast", "burnt toast", "regular toast", "regular toast", "burnt toast", "regular toast", "burnt toast"]

let goodToast = allTheToast.filter(x => x == "regular toast")

goodToast

You can learn more about filter at this link.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

In addition to operators we have learned about before, like + and -, there are operators more operators that return booleans (true or false). Here are two of them: “and” and “or”.

Try these expressions:

1 == 1 && 2 == 2
1 == 1 && 2 == 3
1 == 9 && 0 == 4
1 < 2 && 2 < 3
1 <=  1 && 0 < 0.1
1 <=  1 && 0 > 0.1 

This operator is called the “logical and” operator. What does the && operator do?

Here's another one. What does it do?

1 == 1 || 2 == 2
2 == 3 || 1 == 1
1 == 9 || 0 == 4
2 < 2 || 2 < 3
1 <=  1 || 0 < 0.1
1 <=  2 || 0 > 0.1
1 <=  2 || 0 < 0.1

This operator is called the “logical or” operator. Explain what it does.

(photo from https://www.flickr.com/photos/54397539@N06/5034956030)

We can use all of the methods for arrays that we've learned together to do interesting things. One interesting thing we could do is to simulate some chefs trying to make good toast. Then we could grade the chefs to determine if they pass our standard as “a chef of good toast”. What are the steps?

  1. we make a process for making toast
  2. we organize the toast into categories of “acceptable toast” and “unacceptable toast”
  3. we decide how many pieces of acceptable toast can pass our test
  4. we check all of the toast in a set of toast to see how much of the toast is acceptable toast
  5. we make a list of chefs
  6. we let all of the chefs make some amount of toast
  7. we check all of their toast
  8. we print out a list of chefs of good toast

How can we code all of that? It's possible using some of our useful functions plus forEach, map, and filter.

In our toasting process, we fill an array with several types of toast. We use filter to organize the toast into two categories: acceptable toast and unacceptable toast. After it's organized, we output an object which contains all of the relevant information. We'll call this a toast session.

We'll have another function that can take a list of those sessions and a passing level of acceptable toast that can then return the list of chefs who have passed our test.

We'll have another function that brings these together and runs them in the correct order. We give it a list of chefs to produce toast sessions for. We'll get out an object that contains all of the sessions and the results of our test.

Finally we have to run this with our number for our exact passing level. Then we use forEach to print out who passed. So how exactly can we write that in JavaScript?

//--------------------------------------------------------------------------
//-- toastChefSimulator.js
//--------------------------------------------------------------------------

// some useful functions

function randomInteger (min, max) {
      return Math.floor(min + ((max-min) * Math.random()))
}

function pick (inputArray) {
      return inputArray[randomInteger(0,inputArray.length)]
}

function buildArray (n, fillFunction) {
      let outputArray = [];
      for (let i = 0; i < n; i++) {
              outputArray.push(fillFunction(i))
            }
      return outputArray
}

// our chefs

let toastChefs = ['Kate','Ella','Lynn'];

// functions for our toasting simulator

// our toasting process

function toastBread (person, n) {
    let typesOfToast = ["regular toast", "burnt toast","untoasted bread","perfect toast"];
    let generatedToast = buildArray (n, i => pick (typesOfToast));
    let acceptableToast = generatedToast.filter (t => t == "regular toast" || t == "perfect toast");
    let unacceptableToast = generatedToast.filter (t => t == "burnt toast" || t == "untoasted bread");
    let toastSession =  {
        chef: person,
        numberOfPieces: n,
        totalToastArray: generatedToast,
        acceptableToastArray: acceptableToast,
        numberOfAcceptableToast: acceptableToast.length,
        unacceptableToastArray: unacceptableToast, 
        numberOfUnacceptableToast: unacceptableToast.length 
    };
    return toastSession
}

// find out which chefs have passed our test

function passingChefs (toastSessions, passingLevel) {
    let passingSessions = toastSessions.filter (t => t.numberOfAcceptableToast >= passingLevel);
    let chefs = passingSessions.map (s => s.chef);
    return chefs
}

// bring everything together

function toastChefSimulator (people, numberOfToast, passingLevel) {
    let toastSimulationSessions = people.map(t => toastBread (t, numberOfToast))
    let passed = passingChefs (toastSimulationSessions, passingLevel)
    console.log (passed);
    return {
        sessions: toastSimulationSessions,
        passingChefs: passed
    }
}

// run the simulation; each time you run this, you'll get different results

let toastingSimulation = toastChefSimulator (toastChefs,10,5)

toastingSimulation

// print out the passing chefs with a nice English sentence

toastingSimulation.passingChefs.forEach(c => console.log("Chef " + c + " passed the toast test!"))

Now we want to use filter in p5js to draw. Here's our plan:

  1. set up an example of drawing toast
  2. using filter to change our drawing
  3. drawing with your own class

First, let's have a drawing of toast that we can work with. We'll use different pieces of things that we've done before to make a grid of toast, from uncooked to burnt.

Read through the code below; the comments explain what each section of the code is doing. You should be able to recognize all of the parts.

Now we can use the same example but filter for certain types of toast. Look at line 70. We take the array of Toast objects and then filter for only two colors using the filter method and the logical or operator. That's why only some of the toast appears in the drawing, unlike the previous one. Be sure that you draw the array of filtered Toast, not the original arrray, like in line 76.

At the beginning of the lesson, we talked about doing a new drawing according to these instructions:

  1. draw an animal, plant, or a complicated shape from your imagination
  2. there should be many different versions of it, like sizes and colors
  3. make a class to draw it
  4. use buildArray to fill an array of objects from your class; try to make 100 or more!
  5. use filter to change your drawing in some way

Now you should be able to try to use filter. Give it a try!

  • p5js-week-08.1655566627.txt.gz
  • Last modified: 22 months ago
  • by renick