HIGHER ORDER FUNCTIONS

DECORATORS

HIGER ORDER COMPONENTS

First off,

WTF is a higher order function?

Simply a function that takes in OR returns another function

What are the benefits of having a function take in another function?

function findOdds(arr){
	let temp = []
	for(let i = 0; i < arr.length; i++){
    	if (arr[i] % 2 !== 0) temp.push(arr[i])
    }
    return temp
}

findOdds([1,2,3,4]) // [1, 3]


function findNamesLongerThanFive(arr){
	let temp = []
	for(let i = 0; i < arr.length; i++){
    	if (arr[i].length > 5) temp.push(arr[i])
    }
    return temp
}

findNamesLongerThanFive(['Bryan', 'Charlotte', 'Lindsey', 'June']) // ['Charlotte', 'Lindsey']

A lot of shared code between the two

That is why we have things like .map, .filter & .reduce

(along with a bunch of others)

They take in functions as parameters

Now, WTF is a decorator?

Is this a decorator?

Are these decorators?

Is this a decorator?

@doSomething

For the love of everything holy, Bryan...Yes these are all "decorators"

- You

Decorators

Are literally a way to "decorate" your javascript code with some sort of functionality. 

Decorators are currently a stage 2 proposal from TC39...

TC39

A group of nerds like you and me that decide what ECMAscript will look like. Proposals are made and go through several different stages.

  • Stage 0: Strawman - Seeking input on the proposal
  • Stage 1: Proposal  - Define the why and challenges from adding proposal
  • Stage 2: Draft - Define a specific syntax for proposal
  • Stage 3: Candidate  - Refine proposal
  • Stage 4: Finished  - Ready for the next release of ECMA
function readOnly(target, name, descriptor){
  descriptor.writable = false
  return descriptor
}

Example

  • target - The class we are looking to manipulate
  • name - The property the decorator is modifying
  • descriptor - The property description

Example

To find out what properties are available, we conveniently can use Object.getOwnPropertyDescriptor

const me = {
  name: 'Bryan',
  age: 29,
  tattoos: true,
  family: ['Lindsey', 'Coco', 'June']
}

Object.getOwnPropertyDescriptors(me)
function readOnly(target, name, descriptor){
  descriptor.writable = false
  return descriptor
}

class User {
  constructor(name) {
    this.name = name;
  }
  
  @readOnly
  greet() {
    return this.name + ' says hello'
  }

}

Example Usage

So what?

This makes it so no one can come in and hug stuff up like this:

User.prototype.greet = function(){
  return this.user = " loves to rollerblade"
}

HIGHER ORDER COMPONENTS

HOC

A technique that allows us to share component logic.

Simply put, a function that takes in a Component as a parameter and returns a new Component

Context

Context is a solid option for sharing data between X layers of Components

deck

By bryansmith33

deck

  • 315