avatarAndrew Quan

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

8604

Abstract

<span class="hljs-keyword">const</span> boundFn = fn.<span class="hljs-title function_">bind</span>(<span class="hljs-variable language_">this</span>); <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">defineProperty</span>(<span class="hljs-variable language_">this</span>, key, { <span class="hljs-attr">value</span>: boundFn, <span class="hljs-attr">configurable</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">writable</span>: <span class="hljs-literal">true</span>, }); <span class="hljs-keyword">return</span> boundFn; }, }; }

<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyComponent</span> { <span class="hljs-title function_">constructor</span>(<span class="hljs-params">props</span>) { <span class="hljs-variable language_">this</span>.<span class="hljs-property">props</span> = props; } @autobind <span class="hljs-title function_">handleClick</span>(<span class="hljs-params"></span>) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">props</span>); } }</pre></div><p id="0013">In this example, the decorator is used to decorate the function so that it automatically binds this when called and returns a new function. This way, after instantiating , you don’t need to manually bind this when calling the function.<code>autobindhandleClickMyComponentthis.handleClick()</code></p><h1 id="3ffe">Logging</h1><p id="7a28">Decorators can be used to record logs, including printing information such as function calls, function execution times, etc.</p><div id="1a70"><pre><span class="hljs-keyword">function</span> <span class="hljs-title function_">log</span>(<span class="hljs-params">target, name, descriptor</span>) { <span class="hljs-keyword">const</span> originalMethod = descriptor.<span class="hljs-property">value</span>;

descriptor.<span class="hljs-property">value</span> = <span class="hljs-keyword">function</span> (<span class="hljs-params">...args</span>) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">Function <span class="hljs-subst">${name}</span> called with <span class="hljs-subst">${args}</span></span>); <span class="hljs-keyword">const</span> start = performance.<span class="hljs-title function_">now</span>(); <span class="hljs-keyword">const</span> result = originalMethod.<span class="hljs-title function_">apply</span>(<span class="hljs-variable language_">this</span>, args); <span class="hljs-keyword">const</span> duration = performance.<span class="hljs-title function_">now</span>() - start; <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">Function <span class="hljs-subst">${name}</span> completed in <span class="hljs-subst">${duration}</span>ms</span>); <span class="hljs-keyword">return</span> result; }; <span class="hljs-keyword">return</span> descriptor } <span class="hljs-keyword">class</span> <span class="hljs-title class_">MyClass</span> { @log <span class="hljs-title function_">myMethod</span>(<span class="hljs-params">arg1, arg2</span>) { <span class="hljs-keyword">return</span> arg1 + arg2; } }

<span class="hljs-keyword">const</span> obj = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyClass</span>(); obj.<span class="hljs-title function_">myMethod</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// Output: </span> <span class="hljs-comment">// Function myMethod called with 1,2</span> <span class="hljs-comment">// Function myMethod completed in 0.013614237010165215ms</span></pre></div><h1 id="aff7">Authentication authentication</h1><p id="bbff">Decorators can also be used to check a user’s authentication status and permissions to prevent unauthorized users from accessing sensitive data or performing actions on a regular basis.</p><div id="be1a"><pre><span class="hljs-keyword">function</span> <span class="hljs-title function_">authorization</span>(<span class="hljs-params">target, name, descriptor</span>) { <span class="hljs-keyword">const</span> originalMethod = descriptor.<span class="hljs-property">value</span>;

descriptor.<span class="hljs-property">value</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params">...args</span>) { <span class="hljs-keyword">if</span> (!<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">isAuthenticated</span>()) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Access denied! Not authenticated'</span>); <span class="hljs-keyword">return</span>; } <span class="hljs-keyword">if</span> (!<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">hasAccessTo</span>(name)) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">Access denied! User does not have permission to <span class="hljs-subst">${name}</span></span>); <span class="hljs-keyword">return</span>; } <span class="hljs-keyword">return</span> originalMethod.<span class="hljs-title function_">apply</span>(<span class="hljs-variable language_">this</span>, args); }; <span class="hljs-keyword">return</span> descriptor; }

<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyApi</span> { <span class="hljs-title function_">isAuthenticated</span>(<span class="hljs-params"></span>) { <span class="hljs-comment">// perform authentication check</span> <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>; } <span class="hljs-title function_">hasAccessTo</span>(<span class="hljs-params">endpoint</span>) { <span class="hljs-comment">// perform authorization check</span> <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>; } @authorization <span class="hljs-title function_">getUsers</span>(<span class="hljs-params"></span>) { <span class="hljs-comment">// return users data</span> } @authorization <span class="hljs-title function_">deleteUser</span>(<span class="hljs-params">id</span>) { <span class="hljs-comment">// delete user with id</span> } }</pre></div><h1 id="646e">Cache</h1><p id="3465">Decorators can also be used to cache the execution results of functions to avoid double evaluation.</p><div id="5257"><pre><span class="hljs-keyword">function</span> <span class="hljs-title function_">memoize</span>(<span class="hljs-params">target, name, descriptor</span>) { <span class="hljs-keyword">const</span> originalMethod = descriptor.<span class="hljs-property">value</span>; <span class="hljs-keyword">const</span> cache = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>();

descriptor.<span class="hljs-property">value</span> = <span class="hljs-keyword">function</span> (<span class="hljs-params">...args</span>) { <span class="hljs-keyword">const</span> cacheKey = args.<span class="hljs-title function_">toString</span>(); <span class="hljs-keyword">if</span> (cache.<span class="hljs-title function_">has</span>(cacheKey)) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">cache hit: <span class="hljs-subst">${cacheKey}</span></span>); <span class="hljs-keyword">return</span> cache.<span class="hljs-title function_">get</span>(cacheKey); } <span class="hljs-keyword">const</span> result = originalMethod.<span class="hljs-title function_">apply</span>(<span class="hljs-variable language_">this</span>, args); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">cache miss: <span class="hljs-subst">${cacheKey}</span></span>); cache.<span class="hljs-title function_">set</span>(cacheKey, result); <span class="hljs-keyword">return</span> result; }; <span class="hljs-keyword">return</span> descriptor; }

<span class="hljs-keyword">class

Options

</span> <span class="hljs-title class_">MyMath</span> { @memoize <span class="hljs-title function_">calculate</span>(<span class="hljs-params">num</span>) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'calculate called'</span>); <span class="hljs-keyword">return</span> num * <span class="hljs-number">2</span>; } }

<span class="hljs-keyword">const</span> math = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyMath</span>(); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(math.<span class="hljs-title function_">calculate</span>(<span class="hljs-number">10</span>)); <span class="hljs-comment">// Output: </span> <span class="hljs-comment">// calculate called</span> <span class="hljs-comment">// cache miss: 10</span> <span class="hljs-comment">// 20</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(math.<span class="hljs-title function_">calculate</span>(<span class="hljs-number">10</span>)); <span class="hljs-comment">// Output: </span> <span class="hljs-comment">// cache hit: 10</span> <span class="hljs-comment">// 20</span></pre></div><h1 id="57d9">Aspect-oriented programming</h1><p id="0d61">Decorators can be used to implement facet-oriented programming, that is, to add functionality at runtime without modifying the original code.</p><div id="bc4d"><pre><span class="hljs-keyword">function</span> <span class="hljs-title function_">validate</span>(<span class="hljs-params">target, name, descriptor</span>) { <span class="hljs-keyword">const</span> originalMethod = descriptor.<span class="hljs-property">value</span>;

descriptor.<span class="hljs-property">value</span> = <span class="hljs-keyword">function</span> (<span class="hljs-params">...args</span>) { <span class="hljs-keyword">const</span> isValid = args.<span class="hljs-title function_">every</span>(<span class="hljs-function"><span class="hljs-params">arg</span> =></span> <span class="hljs-keyword">typeof</span> arg === <span class="hljs-string">'string'</span> && arg.<span class="hljs-property">length</span> > <span class="hljs-number">0</span>); <span class="hljs-keyword">if</span> (!isValid) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Invalid arguments'</span>); <span class="hljs-keyword">return</span>; } <span class="hljs-keyword">return</span> originalMethod.<span class="hljs-title function_">apply</span>(<span class="hljs-variable language_">this</span>, args); }; <span class="hljs-keyword">return</span> descriptor; }

<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyForm</span> { @validate <span class="hljs-title function_">submit</span>(<span class="hljs-params">name, email, message</span>) { <span class="hljs-comment">// submit the form</span> } }

<span class="hljs-keyword">const</span> form = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyForm</span>(); form.<span class="hljs-title function_">submit</span>(<span class="hljs-string">''</span>, <span class="hljs-string">'[email protected]'</span>, <span class="hljs-string">'Hello world'</span>); <span class="hljs-comment">// Output: Invalid arguments</span></pre></div><h1 id="c8da">Reversible decorators</h1><p id="5322">Decorators can also be applied in reversible scenes, for example, you can add a reversible decorator to modify function behavior.</p><div id="b868"><pre><span class="hljs-keyword">function</span> <span class="hljs-title function_">reverse</span>(<span class="hljs-params">target, name, descriptor</span>) { <span class="hljs-keyword">const</span> originalMethod = descriptor.<span class="hljs-property">value</span>;

descriptor.<span class="hljs-property">value</span> = <span class="hljs-keyword">function</span> (<span class="hljs-params">...args</span>) { args.<span class="hljs-title function_">reverse</span>(); <span class="hljs-keyword">return</span> originalMethod.<span class="hljs-title function_">apply</span>(<span class="hljs-variable language_">this</span>, args); }; <span class="hljs-keyword">return</span> descriptor; } <span class="hljs-keyword">class</span> <span class="hljs-title class_">MyMath</span> { @reverse <span class="hljs-title function_">calculate</span>(<span class="hljs-params">num1, num2</span>) { <span class="hljs-keyword">return</span> num1 + num2; } }

<span class="hljs-keyword">const</span> math = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyMath</span>(); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(math.<span class="hljs-title function_">calculate</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)); <span class="hljs-comment">// Output: 3</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(math.<span class="hljs-property">calculate</span>.<span class="hljs-title function_">reversed</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)); <span class="hljs-comment">// Output: 3</span></pre></div><h1 id="2ddc">Automatic type checking</h1><p id="037c">Decorators can be applied to automatic type checking, for example, you can add a decorator to ensure that the type of a function parameter is correct.</p><div id="a63a"><pre><span class="hljs-keyword">function</span> <span class="hljs-title function_">checkType</span>(<span class="hljs-params">expectedType</span>) { <span class="hljs-keyword">return</span> <span class="hljs-keyword">function</span>(<span class="hljs-params">target, name, descriptor</span>) { <span class="hljs-keyword">const</span> originalMethod = descriptor.<span class="hljs-property">value</span>;

descriptor.<span class="hljs-property">value</span> = <span class="hljs-keyword">function</span> (<span class="hljs-params">...args</span>) {
      <span class="hljs-keyword">const</span> invalidArgs = args.<span class="hljs-title function_">filter</span>(<span class="hljs-function"><span class="hljs-params">arg</span> =&gt;</span> <span class="hljs-keyword">typeof</span> arg !== expectedType);
      <span class="hljs-keyword">if</span> (invalidArgs.<span class="hljs-property">length</span> &gt; <span class="hljs-number">0</span>) {
        <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Invalid arguments: <span class="hljs-subst">${invalidArgs}</span>`</span>);
        <span class="hljs-keyword">return</span>;
      }
      <span class="hljs-keyword">return</span> originalMethod.<span class="hljs-title function_">apply</span>(<span class="hljs-variable language_">this</span>, args);
    };
    <span class="hljs-keyword">return</span> descriptor;
  }

}

<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyMath</span> { @<span class="hljs-title function_">checkType</span>(<span class="hljs-string">'number'</span>) <span class="hljs-title function_">add</span>(<span class="hljs-params">num1, num2</span>) { <span class="hljs-keyword">return</span> num1 + num2; } }

<span class="hljs-keyword">const</span> math = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyMath</span>(); math.<span class="hljs-title function_">add</span>(<span class="hljs-number">1</span>, <span class="hljs-string">'2'</span>); <span class="hljs-comment">// Output: Invalid arguments: 2</span></pre></div><p id="dd86"><i>More content at <a href="https://plainenglish.io/"><b>PlainEnglish.io</b></a>.</i></p><p id="5cf7"><i>Sign up for our <a href="http://newsletter.plainenglish.io/"><b>free weekly newsletter</b></a>. Follow us on <a href="https://twitter.com/inPlainEngHQ"><b>Twitter</b></a></i>, <a href="https://www.linkedin.com/company/inplainenglish/"><b><i>LinkedIn</i></b></a><i>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><b>YouTube</b></a>, and <a href="https://discord.gg/GtDtUAvyhW"><b>Discord</b></a><b>.</b></i></p><p id="7057"><b><i>Interested in scaling your software startup</i></b><i>? Check out <a href="https://circuit.ooo?utm=publication-post-cta"><b>Circuit</b></a>.</i></p></article></body>

Mental Health

How To Rapidly Overcome Anxiety Through Behavioural Experiments

A simple system to change your relationship with anxiety forever.

Photo by Priscilla Du Preez on Unsplash

In the first half of this year, I found myself with a multitude of life changes that caused a great deal of anxiety. I was unable to sleep on hot, restless nights, and I often had a mind racing with a wide variety of unhealthy thoughts:

  • I worried about the pandemic’s impact on our startup’s viability.
  • I worried about the health of myself and my loved ones.
  • I worried about my finances and keeping a roof on top of my head.
  • In short, I worried about everything.

The impact on my physical health was dire. Every night I’d only end up having 3 to 4 hours of broken sleep, during which I would be subconsciously scratching due to the heat and horrible dreamscapes fuelled by anxiety.

I’d have prolonged migraines and would feel lethargic during the day. I also wouldn’t stop furrowing my eyebrows as I thought through all the scenarios I needed to prepare for mentally in both work and social life.

I realised I needed to make a change, so I bit the bullet: I sought professional advice from a Cognitive Behavioural Therapist (CBT), and it saved my life.

Seeking Help

During my CBT sessions, I was able to learn many tools and techniques to help cope with uncertainty and anxiety in a healthier, more balanced view.

In this article, I walk through what was by far the most useful exercise for a chronic anxious person: the concept of “Behavioural Experiments”. This straightforward system can change your relationship with worry forever.

Defining Cognitive Behavioural Therapy

Photo by Toa Heftiba on Unsplash

Cognitive Behavioural Therapy (CBT) is a type of psychotherapy that aims to help resolve an individual’s problems by identifying unhelpful patterns of thinking and behaviour.

The main idea is that our problems can be broken down into distinct parts that can be worked on individually and therapeutically to bring about positive change. There are many elements to the framework, but if there’s one thing you should learn is that events (situations) lead to thoughts, which lead to feelings (positive or negative), which lead to behaviours.

Outlined below is the CBT Behavioural Experiment framework, which, when applied consistently, can free you from negative thoughts and allow you to begin living life with less doubt and more positivity.

📓 Note: If you are experiencing extreme symptoms of chronic depression and are at risk of harm to yourself or to others, please see your own CBT therapist. For those in the UK, have a look into non-profit organisations such as Mind or get a referral via your public or private doctor or public GP via the NHS.

What Are Behavioural Experiments? Why Use Them?

A behavioural experiment is a method that allows us to test out old and unhelpful beliefs as well as check whether new, more balanced beliefs in a “real-world” context are more relevant. Experiments are often much better for us to learn new perspectives and opinions by actually putting them into action.

It makes a lot of sense to treat this exercise as an experiment. After all, you are already full of anxiety, so any experiment can only reduce that anxiety or have no impact at all — in which case, you are no worse off than before.

There are many different ways to create behavioural experiments in social anxiety, so I’ll explain the framework first, then illustrate using a simplified example towards the end.

The Components of Behavioural Experiments

There are various components of the experiment, but in its most simplistic sense, it contains four main areas:

  1. Situation & Prediction of your Current Thought
  2. Situation & Prediction of an Alternative Thought
  3. The Outcome (after running the experiment)
  4. What You Learned
My illustration of the Behavioural Experiments worksheet

As a reward for reading through the detail of how to use this framework, you will have access to a free worksheet template that you can copy and fill out for yourself. Read below! 👇

1. Situation

Which situations are you most worried about?

Outline the situation that you think has triggered your anxiety. While I can’t give you all of my personal examples, here are my top four adjusted for a public audience:

  1. Public Speaking — “Not spending enough time crafting every word I need to say for major presentations.”
  2. Medium Writing — “Not writing enough articles during the week after my workday is complete.”
  3. Problems Solving At Work — “Not being able to find a solution to my customer’s biggest pain point today.”
  4. Partner Insecurities — “Not fulfilling all of my partner’s needs and wants during the lockdown.”

For the rest of this article, I will focus on example #1 — Public Speaking.

🗒 Note: Running experiments that are often the opposite to your regular thought patterns can be mentally draining. So, for the first time doing this exercise, limit yourself to only a handful of Situations so that you can focus on measuring the outcomes and how you felt during the experiments.

2. Prediction and Belief Rating

What do you believe will happen? What is your belief rating in %?

For the situation you’ve described, jot down your prediction of what will likely happen. Then, assign a ‘belief rating’, the probability (in percentage %) that this prediction will happen.

  • Current Thought Situation and Prediction — “If I don’t think very carefully and plan out every word I say, the audience will think I am incapable and not pay attention to what I am saying.”
  • Current Thought Prediction and Belief Rating — “The audience will ignore me = 90%; the audience will think less of me = 75%.”

Combining the Situation and Prediction gives you your “Current Thought”. It is this Current Thought that you will need to challenge in your experiments, using what is called the “Alternative Thought”.

3. Alternative Thought (Situation + Prediction)

What alternative thought may exist? What do you believe will happen, and what is your belief rating (in %)?”

For the situations described, think about an alternative thought pattern that could you try to prove/disprove your prediction. For the above example, we already identified some potential outcomes for when you don’t think very carefully about each word you say before speaking publicly. So what would happen if you prepared less or use your gut when speaking?

  • Alternative Thought Situation and Prediction: Paying close attention to my thoughts makes it more challenging to find the right words, leading me to stumble in my speech and delivery.
  • Alternative Thought Belief Rating: About 30%.

4. Experiment

What experiments can you run to prove/disprove the validity of your current and alternative thoughts? What safety behaviours should I stop doing?

This step requires us to describe some social experiment that we can use to validate or invalidate our predictions in both the Current Thought pattern and Alternative Thought pattern.

Afterwards, we write a list of ‘safety behaviours’ that we shouldn’t be doing: list of behaviours we risk doing when we are in an anxiety-provoking situation to help cope or keep us safer.

  • Experiment #1: I’m going to present twice this week to different audiences at work. In each presentation, I’m not going to focus on the individual words that come out of my mouth, but I will write a bullet point of the topic to speak about and speak my mind per bullet point.
  • Experiment #2: I will also listen to what the other person says, replay my understanding of their concerns, and then respond spontaneously with whatever comes into my mind.
  • Safety behaviours to stop: Babbling, trying to find “intelligent” words, avoiding eye contact, turning off video during the videoconference to make it more comfortable to speak.

5. Outcome

What actually happened? Where was your attention focused? Was your prediction correct?

It’s important to reflect on the outcomes of the experiment to measure how successful you were and to challenge your core beliefs and thought patterns. For the public speaking example above, here are the outcomes:

  • I presented twice, both to a broad audience of at least ten people per presentation.
  • At first, I found it difficult to speak spontaneously, but this quickly passed once I had been talking for a while. I was much more comfortable by the 2nd presentation around due to newly gained confidence.
  • I found that I was able to hold a reasonable conversation and make a point without obsessing over saying the “right” thing. The words seemed to come out a little easier too.
  • I found that when I took the time to acknowledge the question, replay it back, and speak slower, I was able to think clearer. After gaining feedback, I was told that I sounded more confident as well!

6. What Did You Learn?

What did you learn? Is there a more balanced view than your Current and Alternative Thoughts? If you could re-rate your beliefs for what will happen in future, what would they be? (Belief rating from 0 to 100%).

In some cases, you may want to create another set of “Alternative Thoughts”, especially when your experiment doesn’t go to plan, and the outcome is entirely different from what you expected.

For the example above, no adjustments are necessary as the prediction was reasonably valid. Here’s what I found during this experiment:

  • I can probably stop trying so hard to prepare for presentations and speak from my gut.
  • My words will flow casually, and I will continuously think about saying the right thing stops that flow — it’s counterproductive.
  • Re-rating my belief in my Current Thought prediction: “The audience will ignore me” = 20%, and “the audience will think less of me” = 20%.
  • Re-rating my belief in my Alternative Thought prediction: “I will stumble in my speech and delivery if I think too hard about my words” = 80%

For the above public speaking example, I still have a long way to go in relieving myself from the self-imposed stress of writing high-quality content in quick succession. Yet, I have realised my tendency to worry too much about how people think of me, which is an unsafe mental space to be in. I hope many of you realise the same too!

Conclusion and Free Worksheet

We often get caught up in a vicious thought cycle of anxiety and struggle to test out the beliefs that provide endless fuel to the problem: some core belief that we think is true but may not be.

By becoming our own thought scientists, and by testing these beliefs, we can gather evidence to prove our thoughts, or disprove them completely.

Keeping a simple weekly worksheet on your Current Thoughts, Alternative Thoughts, Experiments, Outcomes and Lessons Learned will allow you to work through your doubts one by one systematically.

I’ve created a template for you to download for free! I simply request that you leave a comment below as to whether:

  1. You were able to successfully run some behavioural experiments to clear your mind of anxious thoughts;
  2. What those experiments were (hopefully not too personal), so that we can share and get over our anxiety together; and
  3. Whether it helped you clear your mind and how you felt at the end of your experiments.
Psychology
Self Improvement
Personal Development
Mental Health
Personal Growth
Recommended from ReadMedium