<![CDATA[Chety's Blog]]><![CDATA[A software engineer who wants to solve every day problem with code.]]>https://chety.hashnode.devRSS for NodeThu, 25 Jun 2026 13:29:25 GMT<![CDATA[en]]>60<![CDATA[Fixed: The file is not `goimports`-ed with ...]]><![CDATA[If you have ever encountered the error below in your IDE, Go is reminding you to follow its rules. Go is quite strict about its rules, and sometimes it's best to say, Yes, my lord, as you wish. Error: File is not goimports -ed with ... To fix this ...]]>https://chety.hashnode.dev/fix-file-is-not-goimports-edhttps://chety.hashnode.dev/fix-file-is-not-goimports-ed<![CDATA[Go Language]]><![CDATA[debugging]]><![CDATA[golang]]><![CDATA[intellij]]><![CDATA[backend]]><![CDATA[IDEs]]><![CDATA[Chety]]>Mon, 22 Apr 2024 08:52:35 GMT<![CDATA[

If you have ever encountered the error below in your IDE, Go is reminding you to follow its rules. Go is quite strict about its rules, and sometimes it's best to say, Yes, my lord, as you wish.

Error: File is not goimports -ed with ...

To fix this problem, we have 2 solutions that I am aware of for now

  1. Execute the manual goimports command with the given file or project root directory as shown below. Ensure that you have goimports installed it on your system.
go install golang.org/x/tools/cmd/goimports@latest #install goimports 

#for a single file
- goimports -w -local path/to/your/project/internal/services/service_multi.go

#for whole project
- goimports -w -local path/to/your/project ./...

2-If you use Goland/IntelliJIDEA, you can automate this setting from the IDE's menu. Navigate to Settings/Editor/Code Style/Go and adjust Sorting type to goimports. After making this adjustment, your IDE will take care of sorting import statements, allowing you to concentrate on your actual tasks.

Until the next error, stay human, and resist AI!

]]><![CDATA[JS Interview Series - 3]]><![CDATA[I recently participated in a JS interview and was asked a couple of questions. I think it is good to share here for both myself and anyone who is lucky enough to see this blog :) Of course, I was not able to answer all of them correctly but at least ...]]>https://chety.hashnode.dev/js-interview-series-3https://chety.hashnode.dev/js-interview-series-3<![CDATA[interview]]><![CDATA[JavaScript]]><![CDATA[jobs]]><![CDATA[Chety]]>Thu, 09 Feb 2023 21:46:51 GMT<![CDATA[

I recently participated in a JS interview and was asked a couple of questions. I think it is good to share here for both myself and anyone who is lucky enough to see this blog :) Of course, I was not able to answer all of them correctly but at least try to show your thought process as can as possible. I am sharing the questions with their explanations below. Feel free to add your favorite interview questions in the comment section.

//Question: What is the output of this code ?

setTimeout(() => {
  console.log(1);
});

new Promise((resolve, reject) => {
  console.log(2);
  resolve();
  console.log(3);
}).then(() => {
  console.log(4);
});

console.log(5);
//Answer: 2 - 3 - 5 - 4 - 1
**ANSWER**:
- SetTimeout will add the code to the WEBAPI and since no timeout is provided
WEBAPI will move this code to the Event Queue immediately. In Event Queue event loop will always check if callstack is empty. If Callstack is empty and there are no pending jobs in Microtask Queue(promises, async operations) then event loop will push this code to the callstack.

- `new Promise(...)` code means this: Promise executor function starts to work immediately. We will see the output of the executor function. First 2 - 3 will be written to the console. Then Promise will be resolved. The next `then` section code will be moved to the Microtask Queue. Microtask queue has a higher precedence than event queue. (Promise > SetTimeout). After all of this there is only once code line to be executed syncronously. (Console.log(5)). And then promise resolve will be executed before settimeout.
//What is the output of below code?

function myFunc() {
  console.log("inside myFunc",this)  
  const a = {
    b: 22,
    method: () => {
      console.log(this);
    },
    method2: function() {
        console.log(this)
    }
  };
  a.method(); 
  a.method2(); 
}
myFunc.call({});
ANSWER:
   `a.method()`:  the result would be {}. Arrow functions do not have this binding. They inherit `this` from their lexical environment. Since Object a's lexical environment is myFunc function and `this` object there is {}. Because {} is explicitly set for `this` object via myFunc.call({}). If this was not set explicitly than this object would be `Window` in browsers and `global` object in node.js environments.  

  `a.method2()`: if you call a "regular method/function" like this, always left side before dot(.) will be your this object. The result would be object `a` itself.
//Reversed a linked list in javascript
//input [1,] -> [2,] -> [3,] -> [4,] -> [5,null]
//output [5,] -> [4,] -> [3,] -> [2,] -> [1,null]

// A linked list item sample
// {
//     value:1,
//     next: {...}
// }

const reverse = (list) => {
    let previous = null
    while (list) {
        const next = list.next;
        list.next = previous;
        previous = list;
        list = next
    }
    return previous
}

//sample object
const list = {
    value: 1,
    next: {
        value:2,
        next: {
            value:3,
            next: {
                value: 4,
                next: {
                    value: 5,
                    next: null
                }
            }
        }
    }
}
const reversedList = reverse(list)
console.log(list)
console.log("-------")
console.log(JSON.stringify(reversedList))

That is from me for Today. I will continue to add new questions when I have new ones. Until then, take care bye bye.

]]>
<![CDATA[Creating Custom Higher Order Functions (Functional programming edition)]]><![CDATA[Hey Folks, In one of my previous articles I talked about how to create our custom higher-order functions(map, filter, reduce,...etc) to understand higher-order functions better. I think we did a pretty good job there. Now I want to rewrite all these ...]]>https://chety.hashnode.dev/fun-with-functional-programminghttps://chety.hashnode.dev/fun-with-functional-programming<![CDATA[JavaScript]]><![CDATA[Functional Programming]]><![CDATA[Recursion]]><![CDATA[higher-order functions]]><![CDATA[Chety]]>Wed, 21 Sep 2022 11:42:13 GMT<![CDATA[

Hey Folks,

In one of my previous articles I talked about how to create our custom higher-order functions(map, filter, reduce,...etc) to understand higher-order functions better. I think we did a pretty good job there. Now I want to rewrite all these 3 functions without mutating any internal state. I will use the functional programming style and recursive a lot. I will also share code samples at the end of the article. Without any further ado, let's start. Code will speak for itself :)

function filter(predicateFn,arr) {
    if(length(arr) === 0) {
        return [];
    }
    const firstElement = head(arr);
    const firstElementFilter = predicateFn(firstElement) ? [firstElement] : [];
    return concat(firstElementFilter, filter(predicateFn,tail(arr)));

}

function map(fn, array) {
  if(length(array) === 0) {
      return [];
  }
  const firstElement  = head(array);
  const firstElementMap = [fn(firstElement)];
  return concat(firstElementMap,map(fn,tail(array)));
}

function reduce(fn,arr,initialValue) {
    if(length(arr) === 0){
        return initialValue;
    }
    const initial = initialValue ?? head(arr);
    const newArr = isPresent(initialValue) ? arr : tail(arr);
    const newInitialValue = fn(initial,head(newArr));
    return reduce(fn,tail(newArr),newInitialValue);
}

function some(predicateFn, arr) {
    for (const value of arr) {
        if(predicateFn(value)){
            return true;
        }
    }
    return false;
}


function isPresent(val) {
    return val !== undefined && val !== null;
}

function length(arr) {
    return arr.length;
}
function head(arr) {
    if(length(arr) === 0){
        return;
    }
    return arr[0];
}

function tail(arr) {
    if(length(arr) === 0){
        return;
    }
    return arr.slice(1);
}

function concat(arr1,arr2) {
    return arr1.concat(arr2);
}

const double = n => n * 2;
const isEven = n => n % 2  === 0;

const isPrime= n => {
    if(n < 2){
        return false
    }
    const wholes = [2,3,5,7];
    const possibleFactors = filter(num => num <= Math.sqrt(n), wholes )
    return !some(num => n % num === 0, possibleFactors)
}


const fizzBuzz = n => {
      let result = ''
      result += 'fizz'.repeat(n % 3 === 0)
      result += 'buzz'.repeat(n % 5 === 0)
      return result || n;
}

const fizzBuzz2 = n => {
      const fizzed = n % 3 === 0 ? 'fizz' : '';
      const buzzed = n % 5 === 0 ? 'buzz' : '';
      return fizzed || buzzed ? fizzed + buzzed : n ;
}

const product = (num1,num2) => num1 * num2;
const sumOfTwo = (num1,num2) => num1 + num2;

const arr = Array(100).fill(0).map((_,i) => i + 1)
console.log('Primes:',filter(isPrime,arr))
console.log('FizzBuzz:',map(fizzBuzz2,arr))
console.log(reduce(sumOfTwo,arr,0))

As I said here are the code samples . Feel free to give any comments/feedback. Until next time Bye bye.

]]>
<![CDATA[Destructing an object in Javascript(Coffee time article)]]><![CDATA[Hello everyone, Recently I was reading a good article(as always) by Kent C. Dodds. In destructing part, he was asking for a code change that will make the object destructing in one line. I am sharing his question and my solution to that. I think it ...]]>https://chety.hashnode.dev/destructing-an-object-in-javascriptcoffee-time-articlehttps://chety.hashnode.dev/destructing-an-object-in-javascriptcoffee-time-article<![CDATA[JavaScript]]><![CDATA[object destructing]]><![CDATA[Chety]]>Mon, 15 Aug 2022 08:42:20 GMT<![CDATA[

Hello everyone,

Recently I was reading a good article(as always) by Kent C. Dodds. In destructing part, he was asking for a code change that will make the object destructing in one line. I am sharing his question and my solution to that. I think it can be beneficial to someone else.

function nestedArrayAndObject() {
  // refactor this to a single line of destructuring...
  const info = {
    title: 'Once Upon a Time',
    protagonist: {
      name: 'Emma Swan',
      enemies: [
        {name: 'Regina Mills', title: 'Evil Queen'},
        {name: 'Cora Mills', title: 'Queen of Hearts'},
        {name: 'Peter Pan', title: `The boy who wouldn't grow up`},
        {name: 'Zelena', title: 'The Wicked Witch'},
      ],
    },
  }
  // const {} = info // <-- replace the next few `const` lines with this
  const title = info.title
  const protagonistName = info.protagonist.name
  const enemy = info.protagonist.enemies[3]
  const enemyTitle = enemy.title
  const enemyName = enemy.name
  return `${enemyName} (${enemyTitle}) is an enemy to ${protagonistName} in "${title}"`
}

The part we will change is const {} = info;. And here is my solution.

const {title,protagonist: {name:protagonistName,  enemies:[,,{name:enemyName,title: enemyTitle}] }} = info

Stay healthy, and keep coding for good.

]]>
<![CDATA[JS Interview Series - 2]]><![CDATA[Hey All, As I said before, I want to add/solve questions that I encountered in my interviews. Therefore we can improve ourselves together. And I am pretty sure these questions will help someone else in their future interviews. Without further ado, ...]]>https://chety.hashnode.dev/js-interview-series-2https://chety.hashnode.dev/js-interview-series-2<![CDATA[JavaScript]]><![CDATA[interview]]><![CDATA[Technical interview]]><![CDATA[fibonacci]]><![CDATA[Web Development]]><![CDATA[Chety]]>Sun, 03 Jul 2022 11:28:57 GMT<![CDATA[

Hey All,

As I said before, I want to add/solve questions that I encountered in my interviews. Therefore we can improve ourselves together. And I am pretty sure these questions will help someone else in their future interviews. Without further ado, let's deep dive into codes.

Write fibonacci function in imperative and then in recursive and then try to increase recursive function's performance with cached recursive and finally write it in tail recursive

function fibonacciImperative(num) {
  let [previous, current] = [0, 1];
  if (num <= 0) {
    return previous;
  }
  if (num === 1) {
    return current;
  }
  for (let i = 2; i <= num; i++) {
    [previous, current] = [current, previous + current];
  }
  return current;
}

function fibonacciRecursive(num) {
  if (num <= 1) {
    return num;
  }
  return fibonacciRecursive(num - 1) + fibonacciRecursive(num - 2);
}
function fibonacciRecursiveWithCache(n) {
  const fiboStore = new Map([
    [0, 0],
    [1, 1],
  ]);
  function inner(num) {
    if (fiboStore.has(num)) {
      return fiboStore.get(num);
    }
    const fibonacci = inner(num - 1) + inner(num - 2);
    fiboStore.set(num, fibonacci);
    return fibonacci;
  }
  return inner(n);
}

function fibonacciTailRecursive(num, previous = 0, current = 1) {
  if (num === 0) {
    return previous;
  }
  if (num === 1) {
    return current;
  }
  return fibonacciTailRecursive(num - 1, current, previous + current);
}

console.log("fibonacciImperative: ", fibonacciImperative(20));
console.log("fibonacciRecursive: ", fibonacciRecursive(20));
console.log("fibonacciRecursiveWithCache: ", fibonacciRecursiveWithCache(20));
console.log("fibonacciTailRecursive: ", fibonacciTailRecursive(20));

Write a curried product function that can be called in various ways defined below.

product(2,3,4,5)(); // 120
product(2,3)(4,5)(); // 120
product(2)(3)(4)(5); // 24
function product(...args){ 
    return function(...args1){
        if(args1.length === 0){
            return args.reduce((acc,num) => acc * num);
        }
        return product(...args,...args1);            
    }     
}

I think a code snippet means 1000 words. If you have any questions about the code please do not hesitate to contact me.

Stay tuned, bye bye

]]>
<![CDATA[JS - Interview Questions Series - 1]]><![CDATA[Hi There, From now on, I want to add some questions and their answers which I encountered during my endless interviews 👀. I am pretty sure, more or less you will face these questions as well. I hope it will help someone else out there. There can be ...]]>https://chety.hashnode.dev/js-interview-1https://chety.hashnode.dev/js-interview-1<![CDATA[JavaScript]]><![CDATA[interview]]><![CDATA[TypeScript]]><![CDATA[Chety]]>Sat, 26 Mar 2022 16:14:03 GMT<![CDATA[

Hi There,

From now on, I want to add some questions and their answers which I encountered during my endless interviews 👀. I am pretty sure, more or less you will face these questions as well. I hope it will help someone else out there. There can be different solutions to each question and if you think you have different/better/elegant ...etc, please do not hesitate to share them with me. I am planning to publish these articles as a javascript interview series. Stay tuned.

Without further ado Let's start⭐️

What is a callback function. What are the disadvantages of using them?

  • As its name indicates, a callback function is nothing more than a function that is called after specific operations.

  • For example, After signing in to a website, this website can show you a welcoming message. We can think of this scenario in code like below 💭

const signInToMyAwsomeSite = (args,greetingCallback) => {
    //some checks , operations
    const [error,result] = ...; //error, result of checking some logic
    return error ? greetingCallback(null,error) : greetingCallback(result,null);
}
  • In the above code, After signing in to a website, If an error occurs we will execute/call our callback function with ...(null, error) and otherwise with ...(data, null)

** As we saw that, what is wrong with callbacks? What are the cons?**

If both the main function and callback functions are our responsibility then there would be fewer disadvantages. Even in this case, we will have to tackle it with callback hells. But let's talk about a different scenario.

  • Let's assume that we are doing a hotel reservation system. Our team is responsible for checking user inputs and some other business logic checks. But the payment is handled by a third party system. We can imagine our code block as below👇
import {paymentCallback} from './thirdParty/services/payment';
const reserveHotel = (args,paymentCallback) => {
    //make some checks for user inputs and relevant business logic
   const creditCardDetails = {
    //... user credit card details
   }
   paymentCallback(creditCardDetails);
}
  • At first, everything might seem ok. But think about it. This creditCardDetails payment method is out of our control. We can not call the payment directly. It is another team's responsibility. But here are some questions that arise after some thinking. 🤔 Will they be able to call it as expected? Will they call it less/more than expected? What if an error occurred in their system, what is the behavior? Will they call the payment again or not? The list goes on and on ...

  • As we can see from the endless list there are lots of things going on out of our control. We can not trust other systems💯 .

  • So what should we do in such a scenario? Luckily we have Promises it in javascript. You can read about promises in one of my previous articles.

Write a fibonacci function that takes a number(n) and returns n of the fibonacci numbers. First write imperative version than recursive and finally iterator version of that function

//Write imperative version of fibonacci(n)
//Output: fibonacci(10) => [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

const fibonacciIterative = (n) => {
   if (n === 1) {
       return [0]
   }
    if (n === 2) {
        return [0,1]
    }
    const result = [0,1]
    const length = result.length
    while (result.length < n) {
       result.push(result[result.length - 2] + result[result.length - 1]);
    }
    return result

}
//fibonacciIterative(10) => => [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
//----------------------------------------------------

const fibonacciRecursive = (n) => {
    if (n === 1) {
       return [0]
   }
    if (n === 2) {
        return [0,1]
    }
    const result = fibonacciRecursive(n - 1);
    result.push(result.at(-1) + result.at(-2))
    return result;   
}
//fibonacciRecursive(5) => [0, 1, 1, 2, 3]
//----------------------------------------------------

function* fibonacciIterator() {
    let [ a, b ] = [ 0, 1]
    while (true) {
        yield a;
        [a, b] = [b, a + b]
    }
}

let i = 0;
const result = []
for (const fib of fibonacciIterator()) {
    if (i++ === 10) {
        break
    }
     result.push(fib)
}
console.log(result) 

/*
const result = []
const iterator = fibonacciIterator();
let i = 0;
while (i++ < 10) {
    result.push(iterator.next().value)
}
console.log(result)
*/

I will talk about how to promisfy a callback function in the upcoming article. By converting our ready callback functions to promise counterparts we will leverage promises' benefits.

Stay positive/healthy, bye-bye. ✌️

]]>
<![CDATA[A Gentle Introduction To Proxy In JavaScript (Part-2)]]><![CDATA[Hi There, I am on the stage for the second part of the Javascript Proxy article. If you did not read the first part, I highly recommend you read it first. Part1 I want to talk about Reflect API and its relation with Proxy today. Reflect is a built-i...]]>https://chety.hashnode.dev/a-gentle-introduction-to-proxy-2https://chety.hashnode.dev/a-gentle-introduction-to-proxy-2<![CDATA[JavaScript]]><![CDATA[proxy]]><![CDATA[interview]]><![CDATA[Chety]]>Sun, 05 Sep 2021 13:43:59 GMT<![CDATA[

Hi There,

I am on the stage for the second part of the Javascript Proxy article. If you did not read the first part, I highly recommend you read it first. Part1

I want to talk about Reflect API and its relation with Proxy today.

Reflect is a built-in object that simplifies the creation of Proxy.

It was said that internal methods, such as [[Get]], [[Set]] and others are specification-only, they can’t be called directly.

The Reflect object makes that somewhat possible. Its methods are minimal wrappers around the internal methods.

Here are examples of operations and Reflect calls that do the same

const user = {};
Reflect.set(user, 'name', 'John'); //is same as user.name = "John";
console.log(user.name); // John

When we normally set the user name as user.name = "Chety"; what is being done behind the scenes Javascript calls its internal [[Set]] method. As we said earlier in this article, these methods are internal and can not be called directly but somehow Reflect API make it possible. Reflect API has corresponding methods for Javascript internal methods(set for [[Set]], get for [[Get]]. Pretty intuitive right?). That means as you call Reflect.set(...), Reflect API will forward this call to the original object which is the internal [[Set]] method in this case.


We can use Reflect it with Proxy also. Below you can find a proxy creation for user. As always explanations will be provided with code :)

let user = {
     name: "Rodik"
}
user = new Proxy(user, {
    get(target,prop,receiver){
        console.log(`GET ${prop}`);
        //Reflect forwards operation to the original object
        return Reflect.get(target,prop,receiver); // or Reflect.get(...arguments)
    },
    set(target,prop,value,receiver){
        console.log(`SET ${prop} = ${value}`);
        //returning a truthy value means success. Otherwise 
        //update operation will not take place
        return Reflect.set(target,prop,value,receiver)
    }
})

user.name; //GET name
user.name = "Miran"; //SET name = Miran

For every internal method, trappable by Proxy, there’s a corresponding method in Reflect, with the same name and arguments as the Proxy trap.

Let us see some code examples, which can be tricky when not used Reflect with Proxy.

let role = {
    _name: "generic role",
    get name(){
        return this._name
    }
}

role = new Proxy(role,{
    get(target,prop,receiver){
        console.log(`GET METHOD CALLED.`);
        return target[prop]
    }
})
console.log(role.name); // GET METHOD CALLED. generic role

const admin = {
    __proto__: role,
    _name: "admin"
}

console.log(admin.name); //it prints generic role , but why ?

In the above code, we expect admin.name as admin but what we got is generic role. It is not what we expected. The reason lies in the Proxy mechanism. Since admin does not have a getter method or property called name, Javascript will look at its prototype which is role. Role object has a name-getter method thus Javascript calls this getter. That getter method invokes get trap which is defined by proxy. In our proxy get trap target is still role and role["name"] returns what? Wait for it... Of course generic role. So is the case resolved? Not quite yet. To solve this issue instead of returning, we should use Reflect.get(...) for forwarding get operation to the original object which in this case is admin. Our get trap should be like below.

      get(target,prop,receiver){
        console.log(`GET METHOD CALLED.`);
        //forward get operation to the original object  
        return Reflect.get(target,prop,receiver);
    }

That is all I have for you today. If you have any questions, comments, etc... just drop in the comments and I will reply as soon as possible. Until the next post, stay tuned, bye-bye.

]]>
<![CDATA[A Gentle Introduction To Proxy In JavaScript (Part-1)]]><![CDATA[Hi Everyone, Today I want to talk about the proxy object in Javascript. It is an advanced topic and also is asked in Coding Interviews. Without any further ado let's start. Proxy is a wrapper around an object, that forwards operations on it to the o...]]>https://chety.hashnode.dev/a-gentle-introduction-to-proxy-1https://chety.hashnode.dev/a-gentle-introduction-to-proxy-1<![CDATA[JavaScript]]><![CDATA[proxy]]><![CDATA[coding]]><![CDATA[interview]]><![CDATA[Technical interview]]><![CDATA[Chety]]>Sat, 04 Sep 2021 17:00:20 GMT<![CDATA[

Hi Everyone,

Today I want to talk about the proxy object in Javascript. It is an advanced topic and also is asked in Coding Interviews. Without any further ado let's start.

Proxy is a wrapper around an object, that forwards operations on it to the object, optionally trapping(intercepting) some of them.

  • It can wrap any kind of object, including classes and functions.

  • Proxy objects are commonly used to log property accesses, validate, format, or sanitize inputs, and so on.

  • As always you can refer here for full context.

  • The syntax is like below

           let proxy = new Proxy(target, { /* traps */});
    
  • The proxy object allows us to create virtual properties and methods, implement default values, observable objects, function decorators and so much more.

  • It can achieve these behaviors via calling internal methods of JavaScript.([[GET]], [[SET]], etc...)

  • For Internal methods, there are corresponding traps in Proxy. We can see from the below table

2.jpg

  • So let's deep dive into code. Explanations will be in the comments

  • Let's say we have an array and we want to return "No Elements Exists" if the index is out of bounds. Also, we want to only add numbers to the array. As you see, we want to intercept array internal methods and make them behave just like we want. Note: Since writing code directly breaks some layouts and does not seem good. So I am sharing the screenshot of the code. I will also share the GitHub address of the code.

1.jpg


Intercepting a method

  • Let's say we have a fetch method used along with the company. At some point, we need to pass a standard header to our API calls. For this case, we need to use a middleware aka interceptor.

  • There is 2 way to implement a middleware:

  • Create a custom wrapper for the fetch method. But this is not the ideal. Because we have to change fetch to fetchWrapper everywhere in the code which seems pretty risky and time-consuming.

  • A better and nicer way is of course using Proxy :). We can use the apply trap to intercept the method execution. Let us see the code :

    3.jpg


Using as a wrapper

  • Imagine we have a function called delay. This function takes a function and a millisecond parameter and executes this function parameter after provided milliseconds. Here we can just return a regular wrapper function instead of a proxy object. But with this, we lose the original function properties like length, name, etc...

    4.jpg


Create private object properties

  • Let's say we assume a property that starts with '_' is `private property of an object.

  • Nobody should access(get), write(set), enumerate(ownKeys) and delete(deleteProperty) it.

  • We can achieve such behavior with Proxy

    5.jpg


Here is another code sample to demonstrate the Proxy API in Javascript.

import { isValidEmail } from './validator.js';

const user = {
  firstName: 'John',
  lastName: 'Doe',
  username: 'johndoe',
  age: 42,
  email: '[email protected]',
};

const userProxy = new Proxy(user, {
  set: (target, prop, value) => {
    if (prop === 'username') {
      if (!/^[a-z]{3,}$/gi.test(value)) {
        throw new Error(
          `username should be all string and at least 3 or more characters length. Found: ${value}`
        );
      }
    } else if (prop === 'email') {
      if (!isValidEmail(value)) {
        throw new Error(`Email should be valid. Found: ${value}`);
      }
    } else if (prop === 'age') {
      if (typeof value !== 'number' || value < 18) {
        throw new Error(
          `Age  should be number and at least 18. Found: ${value}`
        );
      }
    }
    return Reflect.set(target, prop, value);
  },
  get: (target, prop) => {
    console.log(
      `${new Date().toUTCString()} | The value of ${prop} is ${target[prop]}`
    );
    return Reflect.get(target, prop);
  },
});

userProxy.username = 'avbc';
userProxy.username;

I will also write an article about Reflect API in the second part. Until then stay tuned, bye-bye.

Source: Awesome site to learn/master javascript

GitHub Code Samples

]]>
<![CDATA[Yet Another Introduction To Promises(By Code Examples)]]><![CDATA[Hello World, Today I want to share some code snippets about Promises in Javascript. Basically it is about Promise functions. You can find code explanations on the code blocks. I do not want to get into Promise details.(What is a promise? What is exe...]]>https://chety.hashnode.dev/yet-anotherintroduction-to-promises-by-code-exampleshttps://chety.hashnode.dev/yet-anotherintroduction-to-promises-by-code-examples<![CDATA[JavaScript]]><![CDATA[promises]]><![CDATA[ecmascript]]><![CDATA[Chety]]>Tue, 31 Aug 2021 12:32:41 GMT<![CDATA[

Hello World,

Today I want to share some code snippets about Promises in Javascript. Basically it is about Promise functions. You can find code explanations on the code blocks. I do not want to get into Promise details.(What is a promise? What is executor function in Promise constructor? etc...). You can easily find much more detailed information here . Let's jump into the code :)

const p1 = new Promise((resolve,reject) => setTimeout(
 () => resolve("p1 resolved"),1000));
const p2 = new Promise((resolve,reject) => setTimeout(
() => reject("p2 rejected"),2000));
const p3 = new Promise((resolve,reject) => setTimeout(
() => resolve("p3 resolved"),3000));
const p4 = new Promise((resolve,reject) => setTimeout(
() => reject("p4 rejected"),4000));


//With Promise.all if any promise rejected then first rejected promise
//value will be passed to catch clause then section will not be executed at all. 
//if every promise resolved their values will be passed to then 
// clause at corresponding order

//output: -> "p2 rejected"
Promise.all([p1,p2,p3,p4])
.then(([val1,val2,val3,val4]) => console.log(val1,val2,val3,val4))
.catch(err => console.error(err) )

//Promise.allSettled will wait all the promise to settled(resolved or rejected).
//for resolved promise return {status: "fulfilled", value: "p1 resolved"}
//for rejected promise return {status: "rejected", reason: "p2 rejected"}
Promise.allSettled([p1,p2,p3,p4])
.then(([val1,val2,val3,val4]) => console.log(val1,val2,val3,val4))
.catch(err => console.error(err) )


//Promise.race will return first settled(resolved or rejected) promise's value
//output -> First resolved promise value is : p1 resolved
Promise.race([p1,p2,p3,p4])
.then(val => console.log(`First resolved promise value is : ${val}`))
.catch(val => console.log(`First rejected promise value is: ${val}`))


//Promise.any returns first resolved promise value. Does not take 
//rejected promises into account
Promise.any([p1,p2,p3,p4])
.then(val => console.log(`First resolved promise value is : ${val}`))

Stay tuned, Bye bye

]]>
<![CDATA[How to speed up your code(By this little trick)]]><![CDATA[Hi All, Today I want to share a small tip about how to speed up our function by memoization. Memoization is basically saving your function result with the provided arguments. If you call again your function with the same arguments, the result will b...]]>https://chety.hashnode.dev/how-to-speed-codehttps://chety.hashnode.dev/how-to-speed-code<![CDATA[performance]]><![CDATA[C#]]><![CDATA[Recursion]]><![CDATA[Chety]]>Fri, 27 Aug 2021 09:03:06 GMT<![CDATA[

Hi All,

Today I want to share a small tip about how to speed up our function by memoization. Memoization is basically saving your function result with the provided arguments. If you call again your function with the same arguments, the result will be taken from the cache instead of executing the function again. The code I provided will be in C# but it is easy to implement in other languages as well. I also make benchmarks via the Benchmark.NET NuGet package. I will share a screenshot of the performance result at the end. Enough talk let's jump into the code :)

//classic recursive solution to Fibonacci. Nothing new here
public int RecursiveFibonacci(int num)
{
    if (num < 0)
    {
        throw new ArgumentException("number must be >= 0");
    }
    if (num < 2)
    {
        return num;
    }
    return RecursiveFibonacci(num - 1) + RecursiveFibonacci(num - 2);
}

//With C# 8 we can use inline functions. Here internal inline function
//can access outside variable memo hash. It will first check if the result
//presents in hash otherwise first calculate the result and then  add to the
//hash(You can easily implement this in Javascript via closures) 
public int MemoizedFibonacci(int num)
{
    if (num < 0)
    {
        throw new ArgumentException("number  must be >= 0");
    }
    var memo = new Dictionary<int, int> { { 0, 0 }, { 1, 1 } };
    return internalFibonacci(num);

    int internalFibonacci(int num)
    {
        if (memo.ContainsKey(num))
        {
            return memo[num];
        }
        var value = internalFibonacci(num - 1) + internalFibonacci(num - 2);
        memo[num] = value;
        return value;
    }
}

//Good, old and best way. No recursion, no fancy closures ...etc
//And of course the most performant function in benchmark results 
public int ImperativeFibonacci(int num)
{
    int start = 0, end = 1, count = 0;
    while (count++ < num)
    {
        int temp = end;
        end = start + end;
        start = temp;
    }
    return start;
}

And here is the benchmark result performance.png

And my test codes are as below. Stay tuned.

performance2.png

]]>
<![CDATA[SOLID in Action]]><![CDATA[Hello Everyone, I am pretty sure that you hear the term SOLID all the time. Everyone seems to have an opinion about that. Mostly because there are lots of talks when it comes to such as abstract terms. But I want to deep dive into code to understand...]]>https://chety.hashnode.dev/solid-in-actionhttps://chety.hashnode.dev/solid-in-action<![CDATA[JavaScript]]><![CDATA[SOLID principles]]><![CDATA[clean code]]><![CDATA[design patterns]]><![CDATA[Chety]]>Mon, 17 May 2021 12:23:19 GMT<![CDATA[

Hello Everyone,

I am pretty sure that you hear the term SOLID all the time. Everyone seems to have an opinion about that. Mostly because there are lots of talks when it comes to such as abstract terms. But I want to deep dive into code to understand truly. Today I will talk about the Open/Closed Principle.

pankaj-patel-_SgRNwAVNKw-unsplash.jpg


First thing first, what is SOLID. I take the below passage from Wikipedia.

In object-oriented computer programming, SOLID is a mnemonic acronym for five design principles intended to make software designs more understandable, flexible, and maintainable. The principles are a subset of many principles promoted by American software engineer and instructor Robert C. Martin, first introduced in his 2000 paper Design Principles and Design Patterns.

The SOLID concepts are:

  • The Single-responsibility principle: "There should never be more than one reason for a class to change." In other words, every class should have only one responsibility.
  • The Open–closed principle: "Software entities ... should be open for extension, but closed for modification."
  • The Liskov substitution principle: "Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it".
  • The Interface segregation principle: "Many client-specific interfaces are better than one general-purpose interface."
  • The Dependency inversion principle: "Depend upon abstractions, [not] concretions." The SOLID acronym was introduced later, around 2004, by Michael Feathers.

Although the SOLID principles apply to any object-oriented design, they can also form a core philosophy for methodologies such as agile development or adaptive software development.


And here is my understanding :)

  • Single Responsibility: It states that entities/classes/functions should do only one thing. Therefore you will have only one reason to change your code. Less responsibility means less code, that means fewer bugs that means less mess to reason about ( Recursive error. Call stack size exceeded. Please help... Recursive error. Call stack size exceeded. Please help... ok ok I know bad joke :) ). There is no need to provide code samples for this. Usually, code samples for this are trivial and artificial. You got the idea I guess.

  • Open Closed Principle: Entities should be open to extension but close to modification. Waaaaaaaaaaaaw hang on, what? I know, I know I don't understand either. Let's dive into the code and understand truly.

Imagine we have a salary calculator function for a developer. If he/she has cloud skills we will pay $500 more. If he/she is not a developer, our function should return zero. First, let's write code in the traditional way.

const person = {
  isDeveloper: true,
  hasCloudSkill: true,
};
const calculateDeveloperSalary = (person) => {
  if (!person.isDeveloper) {
    return 0;
  }
  let salary = 3500;
  if (person.hasCloudSkill) {
    salary += 500;
  }
  return salary;
};

console.log(calculateDeveloperSalary(person)); // -> 4000

So far so good. Later on, we need to add a feature. The feature says that If a developer has Devops skills pay $500 more. In our existing codebase, our new version is like the below one.

const person = {
  isDeveloper: true,
  hasCloudSkill: true,
  hasDevopsSkill: true,
};
const calculateDeveloperSalary = (person) => {
  if (!person.isDeveloper) {
    return 0;
  }
  let salary = 3500;
  if (person.hasCloudSkill) {
    salary += 500;
  }
  if (person.hasDevopsSkill) {
    salary += 500;
  }
  return salary;
};

console.log(calculateDeveloperSalary(person)); // -> 4500

What actually happened here is that we need to add another if statement in our function. For every new feature, we will have to add another if/case ...etc That is not a good practice because we are modifying our base code. Instead, we should extend our code. When we modify our existing code, that can change existing behavior, break our code semantic. For avoiding these problems we will apply the Open/Closed Principle. Let's dive into code.

const isDeveloper = (person) => person.isDeveloper;
const hasCloudSkill = (person) => person.hasCloudSkill;

const devWithCloud = (p) => isDeveloper(p) && hasCloudSkill(p);
const notDeveloper = (p) => !isDeveloper(p);
const rest = (_) => true;

const devSkillStore = [
  { callback: notDeveloper, response: 0 },
  { callback: devWithCloud, response: 4000 },
  { callback: rest, response: 3500 },
];

const calculateDeveloperSalary = (person) => { 
  return devSkillStore.find((sk) => sk.callback(person)).response;
};

console.log(calculateDeveloperSalary(person)); // -> 4000

So far so good. We separated our functions which every one of them does only one thing(single responsibility) and then combine them to achieve what we want. But the real benefit we gain with this approach is extensibility. If we need to add a new feature we will not modify/change our existing function. We will just extend/add new capabilities. Let's implement DevOps skills implementation.

const isDeveloper = (person) => person.isDeveloper;
const hasDevopsSkill = (person) => person.hasDevopsSkill;
const hasCloudSkill = (person) => person.hasCloudSkill;

const devWithDevops = (p) => isDeveloper(p) && hasDevopsSkill(p);
const devWithCloud = (p) => isDeveloper(p) && hasCloudSkill(p);
const devNinja = (n) => devWithCloud(n) && hasDevopsSkill(n);
const notDeveloper = (p) => !isDeveloper(p);
const rest = (_) => true;

const devSkillStore = [
  { callback: notDeveloper, response: 0 },
  { callback: devNinja, response: 4500 },
  { callback: devWithCloud, response: 4000 },
  { callback: devWithDevops, response: 4000 },
  { callback: rest, response: 3500 },
];

const calculateDeveloperSalary = (person) => { 
  return devSkillStore.find((sk) => sk.callback(person)).response;
};

That is it. We add a new feature without modifying our existing function. That provides great flexibility and velocity in our software development journey. I will discuss other SOLID principles in upcoming articles with code examples. Stay tuned bye-bye.

]]>
<![CDATA[Iterators And Generators For Beginners]]><![CDATA[Hello World, Today I want to talk about iterators and generators in Javascript. Don't worry and keep calm. That will be a Back to the basics article. Let's firstly talk about arrays. As you know they are the most commonly used data structures. They ...]]>https://chety.hashnode.dev/iterators-and-generators-for-beginnershttps://chety.hashnode.dev/iterators-and-generators-for-beginners<![CDATA[JavaScript]]><![CDATA[array]]><![CDATA[array methods]]><![CDATA[generators]]><![CDATA[Chety]]>Mon, 17 May 2021 09:13:44 GMT<![CDATA[

Hello World,

Today I want to talk about iterators and generators in Javascript. Don't worry and keep calm. That will be a Back to the basics article.

Let's firstly talk about arrays. As you know they are the most commonly used data structures. They are also a special kind of object whose keys are indexes in string format. If they are a kind of object, that means you can attach properties to them. We can also easily traverse an array via for, for..of ...etc.

const numbers = [10, 9, 8, 2, 7, 5, 1, 3, 0];
console.log(Object.keys(numbers)); // -> ["0", "1", "2", "3", "4", "5", "6", "7", "8"]

for(const num of numbers){
    console.info(num);
}

But how can we iterate with for..of over an array. Which mechanism/method provides such an ability? Guess what? That's right it is an iterator mechanism. In the below code, I show what is happening under the hood while we traversing an array via for..of

Whenever we use for..of, it will call the underlying data structure's Symbol.iterator() method. If you log the Array.prototype you will see there is a Symbol(Symbol.iterator) function. Thanks to this implementation we can traverse an array without implementing any extra work.

const iter = numbers[Symbol.iterator]();
iter.next();  // -> {value: 10, done: false}
.....
iter.next();  // -> {value: 0, done: false}
iter.next(); // -> {value:undefined, done:true}

So far so good I guess. What if I want to iterate over an object. As I mentioned before we have to a Symbol.iterator() implementation. This function should return an object which has a next() function. This returned object's next function basically returns a result object which has {value: any, done: boolean} format. With every iteration for..of will call your iterator's next function. That's enough for talk let's see the code.

const obj = {
  data: ["item-1", "item-2", "item-3", "item-4", "item-5"],
  [Symbol.iterator]() {
   //We have to keep this reference. Because it is global 
  //in next function.(Long story with this :) )
    const self = this;
    let index = 0;
    return {
      next() {
       //return { value: self.data[index++], done: index === self.data.length };
        if (index < self.data.length) {
          return { value: self.data[index++], done: false };
        }
        return { done: true };

      },
    };
  },
};

for (const value of obj) {
    console.log(value)
}

Great so far. We can traverse an object anymore. But as you see in the next function there is a lot of boilerplate code. It is cumbersome, error-prone ...etc. Instead of writing all the logic manually, we can use Generators to do this job for us.

Generators are a special kind of function that can be paused and played during the execution.

const obj = {
  data: ["item-1", "item-2", "item-3", "item-4", "item-5"],

     // start(*) indicates that it is a  generator
     *[Symbol.iterator]() {
       for (let i = 0; i < this.data.length; i++) {
         yield this.data[i];
       }
     },

//Same as the above.
 // *[Symbol.iterator]() {
 //   yield* this.data;
 // },
};

for (const value of obj) {
    console.log(value)
}

As simple as that. That is for today. Stay tuned bye-bye.

]]>
<![CDATA[Define Object Properties For Dummies]]><![CDATA[Hello World, Today I want to talk about how to define objects and their properties in Javascript. For me, it is a Back to the basics post. Let's dive in. //@ts-check "use strict"; const person = { name: "chety", }; We basically create an object...]]>https://chety.hashnode.dev/define-object-properties-for-dummieshttps://chety.hashnode.dev/define-object-properties-for-dummies<![CDATA[JavaScript]]><![CDATA[Objects]]><![CDATA[Foundation]]><![CDATA[Chety]]>Mon, 17 May 2021 07:09:39 GMT<![CDATA[

Hello World,

Today I want to talk about how to define objects and their properties in Javascript. For me, it is a Back to the basics post. Let's dive in.

//@ts-check
"use strict";

const person = {
  name: "chety",
};

We basically create an object via object literal above. When you define a property like that your property is basically writable, configurable, enumerable by default. What do these mean actually?

  • Writable: Your property value can be changed via assignment if it is true.
  • Configurable: Your property can be deleted from your object if it is true.
  • Enumerable: Your property can be seen when the enumeration process takes place(via for, for ... of)
console.log(Object.keys(person)); // -> [ 'name' ]

Let's create another property via Object.defineProperty.

Object.defineProperty(person, "secretProp", {
  //normally below properties are false by default when creating a property via Object.defineProperty
  writable: false, // -> You can't change property value via assignment
  configurable: false, // -> You can't delete property from object
  enumerable: false, // -> property will not be seen with enumuration process(for, for of ...)

  //If we define get and set then we can not use value property directly
  //value: 42,

  // If we define writable property then we can not use get and set
  //   get(){
  //       return this["_secretProp"]
  //   },
  //   set(value){
  //       this["_secretProp"] = value
  //   }
});

If we want to see our person's keys Object.keys(person) will only return the enumerable properties. If we want to see all the properties(enumerable/nonenumerable) we can use Object.getOwnPropertyNames(person)

console.log(Object.keys(person)); // -> [ 'name' ]
console.log(Object.getOwnPropertyNames(person)); // -> [ 'name', 'secretProp' ]

But what if we want to add a property whose key is a Symbol? Let's try this.

const age = Symbol("age");
person[age] = 33;

So when we try to access our person keys none of the above methods return this new age property. To access all the keys(string, symbol ...etc) we can use Reflect.ownKeys(person)

console.log(Object.keys(person)); // -> [ 'name' ]
console.log(Object.getOwnPropertyNames(person)); // -> [ 'name', 'secretProp' ]
console.log(Reflect.ownKeys(person)); // -> [ 'name', 'secretProp' , Symbol(age)]

That's it for today guys. If you have any ideas, feedbacks ...etc please do not hesitate to share in the comments. Stay tuned bye-bye.

]]>
<![CDATA[Creating Custom Higher Order Functions]]><![CDATA[Hi There, In my previous Map function in Javascript blog post I mentioned, I will make a blog post about how to define our custom map function. Today we are going to do more :) Creating custom map/forEach/filter/reduce higher order functions(HOC fro...]]>https://chety.hashnode.dev/creating-custom-higher-order-functionshttps://chety.hashnode.dev/creating-custom-higher-order-functions<![CDATA[JavaScript]]><![CDATA[Functional Programming]]><![CDATA[functions]]><![CDATA[clean code]]><![CDATA[Chety]]>Sun, 18 Apr 2021 13:40:10 GMT<![CDATA[

Hi There,

In my previous Map function in Javascript blog post I mentioned, I will make a blog post about how to define our custom map function. Today we are going to do more :) Creating custom map/forEach/filter/reduce higher order functions(HOC from now on) is a great way to understand/solidify how things work under the hood.

pankaj-patel-_SgRNwAVNKw-unsplash.jpg

Let us see the code. Comments are added for clarification purposes.

  • Custom Map Function
//Guard clause to avoid collision with 3 party software or ESNext versions
if(!Array.prototype.customMap){
    Array.prototype.customMap = function(callback){
        const result = [];       
        for(let i = 0 ; i< this.length ; i++){
            //Passing array current element,index and original array
           //itself in every callback 
            const itemResult = callback.call(null,this[i],i,this);    
            result.push(itemResult);
        }
        return result;
    }

}

const numbers = [1,2,3,4,5];
const mappedNumbers = numbers.customMap((num,idx,arr) => {
    console.log(`Num= ${num}, Index = ${idx}`);
    console.log("Original Array: ",arr);
    return num * (idx + 1);
})

console.log("Mapped Numbers:",mappedNumbers); 
/* -> 
Num= 1, Index = 0
Original Array:  (5) [1, 2, 3, 4, 5]

Num= 2, Index = 1
Original Array:  (5) [1, 2, 3, 4, 5]

Num= 3, Index = 2
Original Array:  (5) [1, 2, 3, 4, 5]

Num= 4, Index = 3
Original Array:  (5) [1, 2, 3, 4, 5]

Num= 5, Index = 4
Original Array:  (5) [1, 2, 3, 4, 5]

Mapped Numbers: (5) [1, 4, 9, 16, 25]
*/
  • Custom ForEach Function

Since there is no need to return a value from forEach we just call our callback with current item, index and original array respectively .

if(!Array.prototype.customForEach){
    Array.prototype.customForEach = function(callback){            
        for(let i = 0 ; i< this.length ; i++){           
            callback.call(null,this[i],i,this) 
        }
    }
}

const numbers = [1,2,3,4,5];
numbers.customForEach(num => console.log(num ** 2)); // -> 1,4,9,16,25
  • Custom Filter Function
if(!Array.prototype.customFilter){
    Array.prototype.customFilter = function(callback){
        const result = [];
        for(let i = 0 ; i< this.length ; i++){
            //If current item satisfies the criteria(callback result)
            // add it to the result array
            const itemShouldAdd = callback.call(null,this[i],i,this);
            if(itemShouldAdd){
                result.push(this[i]);    
            }             
        }
        return result;
    }
}

const numbers = [1,2,3,4,5];
const evenNumbers = numbers.customFilter(num => num % 2 === 0);
console.log(evenNumbers); // -> [2,4]
  • Custom Reduce Function
if(!Array.prototype.customReduce){
    Array.prototype.customReduce = function(callback,initialValue = undefined){
        //if initial value provided for our reduce function
        //take it as accumulator initial value(startIndex = 0), otherwise
       //assign array first value to accumulator value(startIndex = 1)
        let accumulatorValue = initialValue == undefined ? this[0] : initialValue;
        const startIndex = initialValue == undefined ? 1 : 0;
        for(let i = startIndex ; i< this.length ; i++){
              accumulatorValue = callback.call(null,accumulatorValue,this[i],i,this);          
        }
        return accumulatorValue;
    }
}

const numbers = [1,2,3,4,5];
console.log(numbers.customReduce((acc,num) => acc * num, 5)); // -> 600

As you see we can easily managed to implement these functions by ourselves. If you have anything to add/edit please do not hesitate to share/comment.

You can also get these code snippets from github.

Stay tuned, bye bye.

]]>
<![CDATA[How to safely define a custom property on prototype in Javascript]]><![CDATA[Hello world citizens, I want to share some code snippets about defining properties in Javascript. But first thing first WHY? Why I want to do such a thing? Here comes your answer my friend :) We may need a property to return our array's last eleme...]]>https://chety.hashnode.dev/how-to-safely-define-a-custom-property-on-prototype-in-javascripthttps://chety.hashnode.dev/how-to-safely-define-a-custom-property-on-prototype-in-javascript<![CDATA[JavaScript]]><![CDATA[Objects]]><![CDATA[clean code]]><![CDATA[Chety]]>Tue, 13 Apr 2021 12:49:16 GMT<![CDATA[

Hello world citizens,

I want to share some code snippets about defining properties in Javascript. But first thing first WHY? Why I want to do such a thing? Here comes your answer my friend :)

  • We may need a property to return our array's last element. Because we don't want to type array[array.length - 1 ] every time. We just want to get last element as array.last
  • We may need an orderBy or orderByDesc function that will get a function as parameter , sort according to this function and then return brand new array without changing my original array(Remember Javascript original sort method mutates the source array, we do not want this behavior.)

... and so on.

Sounds good right? Just like Ruby language. Let's see the code.

  • I want to a property called last to get my last element in a array
if(!Array.prototype.last){
    Object.defineProperty(Array.prototype,"last",{
        get(){
            return this.length > 0 ? this[this.length - 1] : undefined 
        }
    })
}

var numbers = [1,2,3,4,5,6,7,8,9,10];
console.log(numbers.last); // 10

Take a look to if check. It is known as Guard clause. Crucial to add, because we do not want to pollute global namespace if there is already defined a property called last(Maybe defined in a third party library, or a new shinny feature that will come with ES2099 :) )

  • Or we want a reject function which rejects elements that satisfies a given criteria (I am sure Rubyists will understand much better :)
if(!Array.prototype.reject){
   //With object define property writable,configurable,enumerable
  // props are set false by default
    Object.defineProperty(Array.prototype,"reject",{
        value(predicate){
            return this.filter(el => !predicate(el))
        }
    })
}

const users =  [
    {
        "id": 1,
        "username": "cambot",
        "favorite_color": "red"
    },
    {
        "id": 2,
        "username": "gypsy",
        "favorite_color": "purple"
    },
    {
        "id": 3,
        "username": "tom",
        "favorite_color": "red"
    },
    {
        "id": 4,
        "username": "crow",
        "favorite_color": "gold"
    },
    {
        "id": 5,
        "username": "joel",
        "favorite_color": "red"
    },
    {
        "id": 6,
        "username": "mike",
        "favorite_color": "blue"
    },
    {
        "id": 6,
        "username": "jonah",
        "favorite_color": "yellow"
    }
]

users.reject(u => u.favorite_color === "red");

/*-> [
    {
        "id": 2,
        "username": "gypsy",
        "favorite_color": "purple"
    },
    {
        "id": 4,
        "username": "crow",
        "favorite_color": "gold"
    },
    {
        "id": 6,
        "username": "mike",
        "favorite_color": "blue"
    },
    {
        "id": 6,
        "username": "jonah",
        "favorite_color": "yellow"
    }
]
*/
  • Or we want to add a where method which will do same job with filter. For some people(Hi there C#,LINQ) where method is much more convenient so lets add it to the array.
if(!Array.prototype.where){    
    Object.defineProperty(Array.prototype,"where", {
        //default to false. If false you can not change or 
        //delete this property from our prototype
        configurable: false, 

         //default to false. If false you can not assign our
         //property to a new value
        writable: false,

        //default to false. If false you will not see this prop in 
        //enumeration process(for, for in, for of ...)
        enumerable: false,
        value(predicate){
            return this.filter(predicate)
        }
    })
}


const numbers = [1,2,3,4,5,6,7,8,9,10]
console.log(numbers.where(num => num > 4)); // [5,6,7,8,9,10]

const isEven = n => n % 2 === 0 ;
console.log(numbers.where(isEven));  // [2,4,6,8,10]
  • Or we want to an orderBy function to order array according to the provided function without mutating original array
if(!Array.prototype.orderBy){
    Object.defineProperty(Array.prototype,"orderBy", {
         // we can assign our orderBy property to another
        // function later on if we want
        writable: true,
        value(predicate){
            //get copy array to prevent original array modification !!!
            const copyArray = this.slice();
            return copyArray.sort((val1,val2) => {
                const firstValue = predicate(val1);
                const secondValue = predicate(val2);
                if(firstValue == null || secondValue == null){
                    return 0;
                }
                if(firstValue === secondValue){
                    return 0;
                }
                return firstValue > secondValue ? 1 : -1;
            })
        }
    })
}
  • Or orderByDesc function which does the above job but in reverse order
if(!Array.prototype.orderByDesc){
    Object.defineProperty(Array.prototype,"orderByDesc", {
        writable: true, 
        value(predicate){
            //get copy array to prevent original array modification.
            const copyArray = this.slice();
            return copyArray.orderBy(predicate).reverse()
        }
    })
}


var people = [
        {name:"chety", salary: 20_000},
        {name:"rodik", salary: 5_000_000},
        {name:"mirko", salary: 500_000},
]
//sort people by their name ascending(From A to Z)
//console.log(people.orderBy(p => p.name)) 

//sort people by their salary ascending(From Smaller to Bigger)
//console.log(people.orderBy(p => p.salary)) 


//sort people by their salary descending
console.log(people.orderByDesc(p => p.salary)) 
console.log(people) ;

That is it for today everyone. Please do not hesitate comment, share ... Have a nice day with JS.

]]>
<![CDATA[Map function in Javascript]]><![CDATA[Hello world, Today I want to share my knowledge about map which is a higher order function in javascript. After this blog post I will make another blog post about creating our custom map function to understand subject deeper. From now on I will cal...]]>https://chety.hashnode.dev/map-function-in-javascripthttps://chety.hashnode.dev/map-function-in-javascript<![CDATA[JavaScript]]><![CDATA[map]]><![CDATA[functions]]><![CDATA[Functional Programming]]><![CDATA[immutable]]><![CDATA[Chety]]>Tue, 13 Apr 2021 09:58:26 GMT<![CDATA[

Hello world,

Today I want to share my knowledge about map which is a higher order function in javascript. After this blog post I will make another blog post about creating our custom map function to understand subject deeper. From now on I will call higher order function as HOC and Javascript as JS in the article. So first thing first what is HOC?. HOC is a regular function which takes or returns another function(map, filter, reduce, forEach, flatMap etc...).

Higher Order Functions are regular functions that take or return another functions

As you will see functions are first class citizens in JS. That means you can treat functions as same as numbers, strings etc... . You can assign a function to a variable, pass a function to another function, return a function from another function.

Functions are first class citizens in JS

muhammad-haikal-sjukri-1NzJggtJ6j4-unsplash.jpg

Credit

As it's name implies that map function will map every item(with the function you provided as parameter. Remember map is HOC.) in your data source/array. It will not mutate/change your original array instead it will return brand new array with the same length. Map will provide 3 arguments to your callback function which are element, index, array. Index and array are optional that means you do not have to define parameters for them.

Enough talk(Salute to an old friend), let's see the action.

const numbers = [1,2,3,4,5];
const squares = numbers.map((number,index,array) => {
    console.log(`Number: ${number}, Index: ${index}`)
    console.log("Original Array: ",array);
    return number * number;
})
//-> output
/*
Number: 1, Index: 0
Original Array:  (5) [1, 2, 3, 4, 5]

Number: 2, Index: 1
Original Array:  (5) [1, 2, 3, 4, 5]

Number: 3, Index: 2
Original Array:  (5) [1, 2, 3, 4, 5]

Number: 4, Index: 3
Original Array:  (5) [1, 2, 3, 4, 5]

Number: 5, Index: 4
Original Array:  (5) [1, 2, 3, 4, 5]
*/

console.log(numbers); // -> [1, 2, 3, 4, 5]
console.log(squares);  // -> [1, 4, 9, 16, 25]

As you see we can access index and original array in our callback function. Map returned a brand new array and didn't mutate/change our original array.

Lets see another program and then finish our blog post.

const person1 = {
    name: "Chety",
    age: 25,
    languages: ["C#","Javascript"]
}

const person2 = {
    name: "Mirko",
    age: 1,
    languages: ["Kotlin","Julia"]
}

const person3 = {
    name: "Rodik",
    age: 9,
    languages: ["Golang","Typescript"]
}

const people = [person1,person2,person3];

We can call map function on our people array. As first option we can provide anonymous function(function that does not have a name) to map


people.map((person) => `${person.name} is ${person.age} years old and can code in ${person.languages}`);

// ->  ["Chety is 25 years old and can code in C#,Javascript", "Mirko is 1 years old and can code in Kotlin,Julia", "Rodik is 9 years old and can code in Golang,Typescript"]

But for readability purposes we can define our callback function separately and then pass as a parameter to Map function.

function personDescription1(person){
    return person.name + " is " + person.age + " years old and can code in " + person.languages;
}

function personDescription2(person){
    return `${person.name} is ${person.age} years old and can code in  ${person.languages}`;
}

function personDescription3({name,age,languages}){
    return `${name} is ${age} years old and can code in  ${languages}`;
}

const personDescriptionLatest = ({name,age,languages}) => `${name} is ${age} years old and can code in  ${languages}`;

//Below calls produce same results :)
//people.map(personDescription1);
//people.map(personDescription2);
//people.map(personDescription3);
people.map(personDescriptionLatest); 
//output: ["Chety is 25 years old and can code in  C#,Javascript", "Mirko is 1 years old and can code in  Kotlin,Julia", "Rodik is 9 years old and can code in  Golang,Typescript"]

As you see we wrote an anonymous function and 4 different callbacks that return same output with map function. In these functions we use string interpolation with ${} and object destructing via {}. I will also add blog posts about these concepts

Social Message

There is always more than one way to achieve same result in JS.

In the next blog post we will write our custom map function. Stay tuned :).

Please do not hesitate to share, comment, criticize.

Have a nice day with JS :)

]]>
<![CDATA[Different Ways To Get Sh.t Done!(And always bet on Javascript)]]><![CDATA[Hi Everyone, This is my first blog post. In this post I want to share some code snippets to make squares of a given number array. We have to realize that there isn't only one true answer in Javascript world. We always have different approaches and m...]]>https://chety.hashnode.dev/different-ways-to-get-sht-doneand-always-bet-on-javascripthttps://chety.hashnode.dev/different-ways-to-get-sht-doneand-always-bet-on-javascript<![CDATA[JavaScript]]><![CDATA[functions]]><![CDATA[array methods]]><![CDATA[Chety]]>Mon, 12 Apr 2021 07:29:15 GMT<![CDATA[

Hi Everyone,

This is my first blog post. In this post I want to share some code snippets to make squares of a given number array. We have to realize that there isn't only one true answer in Javascript world. We always have different approaches and methods to do things. As Linus Torvalds says

Talk is cheap(not actually Linus come on buddy ), Show me the code.

function makeSquaresRecursive(numbers: any[]) {
    const result: Array<number> = [];

    numbers.forEach((element: any) => {
        if (typeof element === "number") {
            result.push(element ** 2);
        } else {
            const innerResult = makeSquaresRecursive(element);
            result.push(...innerResult);
        }
    });
    return result;
}

function makeSquaresWithFlatMap(numbers: any[]) : any[] {
    return numbers.flatMap((element: any) => {
        if (typeof element === "number") {
            return element ** 2;
        }
        return makeSquaresWithFlatMap(element);
    });
}

function makeSquaresWithFlatAndMap(numbers: any[]) {
    return numbers.flat(10).map(num => num ** 2)
}

function makeSquaresWithToString(numbers: any[]) {
    return numbers.toString().split(",").map(item => Number(item) ** 2);
}


const nums = [1, 2, [3, 4, [5, 6, [7, [8, 9, [10]]]]]];
// ->  [1,3,9,16,25,36,49,64,81,100]

console.log(makeSquaresRecursive(nums));
console.log(makeSquaresWithFlatMap(nums));
console.log(makeSquaresWithFlatAndMap(nums));
console.log(makeSquaresWithToString(nums));

As you see from above we achieved same results with different methods. Please do not hesitate to share, comment :)

If you interested here is the gist of the above code snippets. Enjoy. https://gist.github.com/chety/0528eda00106346623a5b44b4f8bb396

]]>