<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: buddha lama</title>
    <description>The latest articles on DEV Community by buddha lama (@idolentbudha).</description>
    <link>https://dev.to/idolentbudha</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F571186%2F9bf2a86e-2524-4647-b1f7-138a58cbab3b.png</url>
      <title>DEV Community: buddha lama</title>
      <link>https://dev.to/idolentbudha</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/idolentbudha"/>
    <language>en</language>
    <item>
      <title>BackToBasics:How To Run and Debug TypeScript Scripts with ts-node</title>
      <dc:creator>buddha lama</dc:creator>
      <pubDate>Tue, 03 Dec 2024 05:50:57 +0000</pubDate>
      <link>https://dev.to/idolentbudha/backtobasicshow-to-run-and-debug-typescript-scripts-with-ts-node-4ad6</link>
      <guid>https://dev.to/idolentbudha/backtobasicshow-to-run-and-debug-typescript-scripts-with-ts-node-4ad6</guid>
      <description>&lt;p&gt;Sometimes latest new techs just pile up, and in the process of using them, we tend to forget the basics and foundations. It is good to go back and start from scratch to understand the foundation and basics.&lt;/p&gt;

&lt;h2&gt;
  
  
  Introduction:
&lt;/h2&gt;

&lt;p&gt;Typescript is an additional layer to JS that adds type safety. It cannot compile on its own. So it needs a separate compiler to compile to JS before running it. &lt;code&gt;tsc&lt;/code&gt; is the TS compiler that does that work.&lt;br&gt;
But wait, then what the hell is ts-node?&lt;br&gt;
Okay, till now we know that &lt;code&gt;tsc&lt;/code&gt; is a compiler that compiles TS to JS to run the code. Till now there is no Node.js in action. If you want to use TS with Node.js, using &lt;code&gt;tsc&lt;/code&gt; does not make sense. What we really want is just code in TS and let node handle everything. So, ts-node does that for us. We setup ts-node, and it will enable us to run Typescript directly in Node. Amazing, right?&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;code&gt;tsc&lt;/code&gt; vs &lt;code&gt;node-ts&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;If we were using &lt;code&gt;tsc&lt;/code&gt;, we have to run &lt;code&gt;tsc tsfile.ts&lt;/code&gt; command every time and then run the generated JS file.&lt;br&gt;
If we use ts-node, we use &lt;code&gt;ts-node tsfile.ts&lt;/code&gt;, and boom it will execute the code.&lt;br&gt;
I am not going to write every step to make a project run with ts-node. I followed this steps form digitalocean. &lt;a href="https://www.digitalocean.com/community/tutorials/typescript-running-typescript-ts-node" rel="noopener noreferrer"&gt;https://www.digitalocean.com/community/tutorials/typescript-running-typescript-ts-node&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The steps above in the link did not work out of the box for me, it might happen to you too, so make sure:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You have initialized a "tsconfig.json" file, I did that with &lt;code&gt;npx tsc --init&lt;/code&gt;. It just initializes a tsconfig.json file.&lt;/li&gt;
&lt;li&gt;If it shows an error related to the --loader flag, use this option "scripts": &lt;code&gt;{ "start": "NODE_OPTIONS=\"-r ts-node/register --no-warnings\" node index.ts" }&lt;/code&gt; 
&lt;a href="https://www.npmjs.com/package/ts-node#node-flags-and-other-tools" rel="noopener noreferrer"&gt;https://www.npmjs.com/package/ts-node#node-flags-and-other-tools&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Debugging in vscode
&lt;/h2&gt;

&lt;p&gt;To start debugging, we just need to update the &lt;code&gt;launch.json&lt;/code&gt;. I took the code from this &lt;a href="https://gist.github.com/cecilemuller/2963155d0f249c1544289b78a1cdd695" rel="noopener noreferrer"&gt;gist&lt;/a&gt; file.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;{&lt;br&gt;
    // Use IntelliSense to learn about possible attributes.&lt;br&gt;
    // Hover to view descriptions of existing attributes.&lt;br&gt;
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387&lt;br&gt;
    "version": "0.2.0",&lt;br&gt;
    "configurations": [&lt;br&gt;
        {&lt;br&gt;
            "type": "node",&lt;br&gt;
            "request": "launch",&lt;br&gt;
            "name": "Launch Program",&lt;br&gt;
            "args": ["${relativeFile}"],&lt;br&gt;
            "runtimeArgs": ["--nolazy", "-r", "ts-node/register/transpile-only"],&lt;br&gt;
            "args": ["src/script.ts", "--example", "hello"],&lt;br&gt;
            "cwd": "${workspaceFolder}",&lt;br&gt;
            "skipFiles": [&lt;br&gt;
                "&amp;lt;node_internals&amp;gt;/**"&lt;br&gt;
            ],&lt;br&gt;
            "program": "${workspaceFolder}/index.ts",&lt;br&gt;
            "outFiles": [&lt;br&gt;
                "${workspaceFolder}/**/*.js"&lt;br&gt;
            ]&lt;br&gt;
        }&lt;br&gt;
    ]&lt;br&gt;
}&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Alternative
&lt;/h2&gt;

&lt;p&gt;You can use &lt;a href="https://www.npmjs.com/package/tsx" rel="noopener noreferrer"&gt;tsx&lt;/a&gt; which seems to work out of the box unlike ts-node, which always has some difficulty setting up.&lt;br&gt;
If you are just experimenting and digging up, understanding basics and foundations: make mistakes, give yourself time to learn and grow more.&lt;/p&gt;

&lt;h2&gt;
  
  
  Some FlashCard questions
&lt;/h2&gt;

&lt;p&gt;I usually make flashcards for active recall. Here are some flashcard questions while doing this blog:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;What is TypeScript? How does it differ from JavaScript?&lt;/li&gt;
&lt;li&gt;What is the role of the tsc compiler? When is it used?&lt;/li&gt;
&lt;li&gt;What is ts-node? How does it differ from tsc?&lt;/li&gt;
&lt;li&gt;Why would you use ts-node over tsc during development?&lt;/li&gt;
&lt;li&gt;What is the purpose of the tsconfig.json file?&lt;/li&gt;
&lt;li&gt;ESModule vs Common JS Module?&lt;/li&gt;
&lt;li&gt;In Node.js, what is node_options and what is it used for?&lt;/li&gt;
&lt;li&gt;Are the changes made by node_options permanent?&lt;/li&gt;
&lt;li&gt;What is the "cross-env" package in Node and why use it even though the same functionality can be achieved using system tools like shell?&lt;/li&gt;
&lt;li&gt;Which JS engine is Node based upon?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Happy Coding, Happy Learning 🎉&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Delegate Design Pattern in Swift</title>
      <dc:creator>buddha lama</dc:creator>
      <pubDate>Wed, 17 Jul 2024 13:00:03 +0000</pubDate>
      <link>https://dev.to/idolentbudha/understanding-the-delegate-design-pattern-1fph</link>
      <guid>https://dev.to/idolentbudha/understanding-the-delegate-design-pattern-1fph</guid>
      <description>&lt;h2&gt;
  
  
  What is the Delegate Design Pattern?
&lt;/h2&gt;

&lt;p&gt;The Delegate Design Pattern is used when one object needs to use another object to perform a task or action. It's like having a personal assistant – you delegate tasks to them, but you're still in charge.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Use It?
&lt;/h2&gt;

&lt;p&gt;The beauty of this pattern lies in its ability to tie objects together for specific tasks while keeping them responsible for different things. It's all about teamwork without losing individual identity.&lt;/p&gt;

&lt;h2&gt;
  
  
  Key Players: Delegator and Delegate
&lt;/h2&gt;

&lt;p&gt;In this pattern, we have two main characters:&lt;/p&gt;

&lt;p&gt;The Delegator: This is the object that sends the signal. Think of it as the boss giving orders.&lt;br&gt;
The Delegate: This is the object that receives the signal and performs the action. It's like the employee carrying out the tasks.&lt;/p&gt;
&lt;h2&gt;
  
  
  The Secret Sauce: Protocols
&lt;/h2&gt;

&lt;p&gt;Now, here's where it gets interesting. The Delegate Pattern often uses protocols (similar to interfaces in Java). These protocols are like a contract between the Delegator and the Delegate.&lt;/p&gt;
&lt;h2&gt;
  
  
  Why Protocols?
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Loose Coupling:&lt;br&gt;
Protocols help in loosely coupling the objects. This means the Delegator and Delegate aren't tightly bound to each other.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Limited Access:&lt;br&gt;
The Delegator only knows about the methods and properties defined in the protocol. It's like giving someone a to-do list without revealing all your secrets.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Reusability:&lt;br&gt;
Can be used in various scenarios with different delegate implementations.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  In Practice
&lt;/h2&gt;

&lt;p&gt;Imagine you're building a quiz app. The main quiz controller (Delegator) doesn't need to know how to calculate scores – it just needs to know that it can ask something else to do it. So, it delegates this task to a score calculator (Delegate) through a protocol.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Protocol for the Score Calculator Delegate
protocol ScoreCalculatorDelegate {
    func calculateScore(for answers: [String]) -&amp;gt; Int
}

// Quiz Controller (Delegator)
class QuizController {
    var delegate: ScoreCalculatorDelegate?
    private let correctAnswers = ["A", "B", "C"]

    func runQuiz() {
        print("Welcome to the Quiz! Please answer A, B, or C for each question.")
        var userAnswers: [String] = []

        for i in 1...3 {
            print("Question \(i): What's your answer?")
            if let answer = readLine() {
                userAnswers.append(answer.uppercased())
            }
        }

        if let score = delegate?.calculateScore(for: userAnswers) {
            print("Quiz completed! Your score is: \(score) out of 3")
        } else {
            print("Quiz completed, but score couldn't be calculated.")
        }
    }
}

// Score Calculator (Delegate)
class SimpleScoreCalculator: ScoreCalculatorDelegate {
    func calculateScore(for answers: [String]) -&amp;gt; Int {
        let correctAnswers = ["A", "B", "C"]
        return zip(answers, correctAnswers).filter { $0 == $1 }.count
    }
}

// Usage
let quizController = QuizController()
let scoreCalculator = SimpleScoreCalculator()
quizController.delegate = scoreCalculator

quizController.runQuiz()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, QuizController doesn't care how the score is calculated. It just knows it can ask its delegate to do it.&lt;br&gt;
Wrapping Up&lt;br&gt;
The Delegate Design Pattern is a fantastic way to keep your code organized, flexible, and maintainable. By separating responsibilities and using protocols, you create a system where objects can work together harmoniously without losing their individual purposes.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>JS Function Factories</title>
      <dc:creator>buddha lama</dc:creator>
      <pubDate>Thu, 21 Sep 2023 16:28:59 +0000</pubDate>
      <link>https://dev.to/idolentbudha/js-function-factories-20nm</link>
      <guid>https://dev.to/idolentbudha/js-function-factories-20nm</guid>
      <description>&lt;p&gt;A &lt;code&gt;function factory&lt;/code&gt; is a design pattern that includes creating and returning a function from another function.&lt;/p&gt;

&lt;p&gt;Closure is used to achieve this pattern. Function factory can encapsulate configurations within functions. It is used to create multiple functions with similar behaviors.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function createOperation(operation){

  return function(a,b){
    switch (operation){
        case 'add': return a+b;
      case 'minus': return  a-b;
      default:
      return NaN;
    }
  }

}
const addition = createOperation('add');
console.log("addition:",addition(1,2))


const expo = createOperation('exponent');
console.log("Exponent:",expo(1,2))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Output:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsvx1no93y2rjzz30wxbe.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsvx1no93y2rjzz30wxbe.png" alt="Image description" width="514" height="128"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>this in JS</title>
      <dc:creator>buddha lama</dc:creator>
      <pubDate>Tue, 19 Sep 2023 06:45:42 +0000</pubDate>
      <link>https://dev.to/idolentbudha/this-in-js-3njg</link>
      <guid>https://dev.to/idolentbudha/this-in-js-3njg</guid>
      <description>&lt;h2&gt;
  
  
  Back to basics: &lt;code&gt;this&lt;/code&gt; keyword
&lt;/h2&gt;




&lt;p&gt;&lt;code&gt;this&lt;/code&gt; represents the current execution context.&lt;br&gt;
&lt;code&gt;this&lt;/code&gt; may vary based on different scenarios&lt;/p&gt;
&lt;h2&gt;
  
  
  Global Context
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;this&lt;/code&gt; in the global context represents the window [browser environment]&lt;/p&gt;
&lt;h2&gt;
  
  
  Function Context
&lt;/h2&gt;

&lt;p&gt;In a regular function, &lt;code&gt;this&lt;/code&gt; varies based on how the function is invoked.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: this behaves differently for arrow functions&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Function as method:&lt;/strong&gt; If the function is invoked as a method of an object. &lt;code&gt;this&lt;/code&gt; represents the object containing the function&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Function as Standalone function:&lt;/strong&gt; &lt;code&gt;this&lt;/code&gt; represents the global context if the strict-mode is not enabled, in other case the &lt;code&gt;this&lt;/code&gt; is undefined
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const obj = {
  name: "John Doe",
  sayHello: function () {
    console.log("The name is " + this.name);
  }
};

//function as method
obj.sayHello(); // The name is John Doe

//function as standalone function
let sayHelloFn = obj.sayHello;
sayHelloFn(); // this is undefined and throws TypeError: Cannot read properties

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  Constructor Context
&lt;/h2&gt;

&lt;p&gt;When a function is constructed using a &lt;code&gt;new&lt;/code&gt; keyword. &lt;code&gt;this&lt;/code&gt; represents the object that is newly created.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/**
 * Construction Context: 
 * this keyword represents the newly created object
 */
function Person(gender) {
  this.gender = gender;
}
const person = new Person("male");
console.log(person.gender); //male 

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Event Handler
&lt;/h2&gt;

&lt;p&gt;In case of the event handler, &lt;code&gt;this&lt;/code&gt; keyword represents the element of the DOM that triggers the event&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/**
 * Event handler
 */
const button = document.querySelector('button');
button.addEventListener('click', function() {
  console.log(this); // The button element that was clicked
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Arrow Function
&lt;/h2&gt;

&lt;p&gt;Unlike the regular functions, the &lt;code&gt;this&lt;/code&gt; value is not determined by how the function is invoked. Rather, &lt;code&gt;this&lt;/code&gt; is determined by the context in which the function is defined. It is lexically scoped.&lt;/p&gt;

&lt;p&gt;This difference that makes the arrow function useful is when you want to maintain &lt;code&gt;this&lt;/code&gt; from the surrounding code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const obj = {
  name: "OJ",
  printName() {
    console.log(this.name);
  },
  normalFunction: function () {
    return this;
  },
  arrowFunction: () =&amp;gt; {
    return this;
  }
};

console.log(obj.printName());

/**
 * Normal function
 *  **/
//method is invoked
console.log("normalFunction:", obj.normalFunction()); // obj
//standalone function in invoked
const extNormalFunction = obj.normalFunction;
console.log("extNormalFunction:", extNormalFunction()); //global object when strict mode is off, otherwise undefined

/**
 * Arrow Function
 */
console.log("arrowFunction:", obj.arrowFunction()); //global/window object
const extArrowFunction = obj.arrowFunction;
console.log("extArrowFunction:", extArrowFunction()); //global/window object


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>javascript</category>
    </item>
  </channel>
</rss>
