teleren/devto huggingface dataset:
Clone an array in ES 6
Published: 2022-08-07 23:46:49

When we need to copy an array, we often times used slice. But with ES6, you can also use the spread operator to duplicate an array. Pretty nifty, right 🤩

```
const sheeps = ['🐑', '🐑', '🐑'];

// Old way
const cloneSheeps = sheeps.slice();

// ES6 way
const cloneSheepsES6 = [...sheeps];
```
##Why Can’t I Use = to Copy an Array?
Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array under a new value variable. That way this new array does not reference to the old array address in memory.

```
const sheeps = ['🐑', '🐑', '🐑'];

const fakeSheeps = sheeps;
const cloneSheeps = [...sheeps];

console.log(sheeps === fakeSheeps);
// true --> it's pointing to the same memory space

console.log(sheeps === cloneSheeps);
// false --> it's pointing to a new memory space
```
##Problem with Reference Values
If you ever dealt with Redux or any state management framework. You will know immutability is super important. Let me briefly explain. An immutable object is an object where the state can't be modified after it is created. The problem with JavaScript is that arrays are mutable. So this can happen:

```
const sheeps = ['🐑', '🐑'];

const sheeps2 = sheeps;

sheeps2.push('🐺');

console.log(sheeps2);
// [ '🐑', '🐑', '🐺' ]

// Ahhh 😱 , our original sheeps have changed?!
console.log(sheeps);
// [ '🐑', '🐑', '🐺' ]
```
That's why we need to clone an array:

```
const sheeps = ['🐑', '🐑'];

const sheeps2 = [...sheeps];

// Let's change our sheeps2 array
sheeps2.push('🐺');

console.log(sheeps2);
// [ '🐑', '🐑', '🐺' ]

// ✅ Yay, our original sheeps is not affected!
console.log(sheeps);
// [ '🐑', '🐑' ]
```
##Mutable vs Immutable Data Types
Mutable:

- 
object

- 
array

- 
function

- 
Immutable:

All primitives are immutable.

- 
string

- 
number

- 
boolean

- 
null

- 
undefined

- 
symbol


##Shallow Copy Only
Please note spread only goes one level deep when copying an array. So if you're trying to copy a multi-dimensional arrays, you will have to use other alternatives.

```
const nums = [[1, 2], [10]];

const cloneNums = [...nums];

// Let's change the first item in the first nested item in our cloned array.
cloneNums[0][0] = '👻';

console.log(cloneNums);
// [ [ '👻', 2 ], [ 10 ], [ 300 ] ]

// NOOooo, the original is also affected
console.log(nums);
// [ [ '👻', 2 ], [ 10 ], [ 300 ] ]
```
Here's an interesting thing I learned. Shallow copy means the first level is copied, deeper levels are referenced.
##Community Input
Array.from is Another Way to Clone Array

```
const sheeps = ['🐑', '🐑', '🐑'];

const cloneSheeps = Array.from(sheeps);
```
High-Entropy Passphrases
Tags: adventofcode, algorithms, programming, javascript
Published: 2022-08-07 23:37:24

## [Advent of Code 2017 Day 4](https://adventofcode.com/2017/day/4)

## Part 1
1. Inventory Management System Redux!
2. Writing my working algorithm

### Inventory Management System Redux!
- Remember [2018 Day 2](https://adventofcode.com/2018/day/2)?
- It asked me to find exact counts of letters within strings
- This feels similar, but easier, in my opinion
- Because I don't need to build an object of letter counts for each string
- I just need an `Array` and a `Set`, so I can compare `length` and `size`!

### Writing my working algorithm
```
Split the input at each newline character into an array of strings

For each string, accumulate a tally, starting at 0
  Split the string at each space character into an array of strings
  If the length of the array is the same as the size of a Set generated from that array
    Increment the tally by 1, because there are no duplicate phrases
  Else
    Leave the tally unchanged

Return the tally
```

In JavaScript, I use `reduce()`, `split()`, `Array.length`, `Set.size` and a `ternary operator` in a one long chained statement:
```js
input.split('\n')
     .reduce((tally, current) => {
       return tally += current.split(' ').length 
                    == new Set(current.split(' ')).size 
                    ? 1 : 0
     }, 0)
```

## Part 2
1. What a delightful twist!
2. Three `reduce()`rs, that's how!
3. Revealing my working `reduce()`rs

### What a delightful twist!
- Anagrams, eh? How fun!
- And also...complicating

Hmm...how should I attempt to solve this?

### Three `reduce()`rs, that's how!
This is going to get complex really fast, so bear with me:
1. An outer `reduce()` to track the tallies of valid passphrases
2. An inner `reduce()` to collect all the stringified letter tallies for each word
3. An inner-most `reduce()` to generate a stringified letter tally for one word

This animation illustrates each of the `reduce()`rs using the last example set of passphrases:
![Animation of all three reducers](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p17oihzxxkwqldbdvtf9.gif)

### Revealing my working `reduce()`rs
This is the JavaScript I'm proud to have written in about 15 minutes:
```js
return input
  .split('\n')
  .reduce((passphrases, passphrase) => {
    let letterCounts = passphrase
      .split(' ')
      .reduce((list, group) => {
        let counts = group
          .split(' ')
          .reduce((tallies, letter) => {
            tallies[letter] = (tallies[letter] || 0) + 1
            return tallies
          }, {})
        list.push(
          Object.keys(counts)
            .sort()
            .map(el => el + '|' + counts[el]).join(''))
        return list
      }, [])
    return passphrases += letterCounts.length 
                       == new Set(letterCounts).size 
                       ? 1 : 0
  }, 0)
```

## I did it!!
- I solved both parts!
- I used a ton of `reduce()`!
- I made a detailed GIF showing what each `reduce()` does!
- I really enjoyed solving Part 2!
- I'm now tied for my personal best star score in a given year: `40`!
Why I can't decide how to convert a string into a number in JS
Tags: javascript, webdev, beginners, tutorial
Published: 2022-08-07 23:09:00

As mentioned in the title of this post. We will be exploring a few methods you can use to cast strings into numbers and avoid being trapped in a hell of methods.

## parseInt( ) vs parseFloat( )
First of all, when talking of string casting we can't avoid mentioning these very well-known methods.

So, for the ones who are new to javascript, let me tell you, that these methods are used to convert a string into an integer number "parseInt( )" or a float number "parseFloat( )" respectively.

But, there is a tiny problem with both, you have to be aware of the type of number you want to operate with from the beginning because parsing to an incorrect number can produce a lot of mistakes, that can be super harmful to your business.


``` JavaScript
const stringNumber = "45.1"

// output -> 45 (is not a string anymore)
const int = parseInt(stringNumber) 

// output -> 45.1 (is not a string anymore, and it is float)
const float = parseFloat(stringNumber) 
```

## Number( )
This is directly an instance of the javascript's Number class.

Number( ), is one of the most recommended ways to parse strings in numbers since is legible enough to be in large-scale code bases and its functionality can be clearly understood by its name also formats a string in Integer or Float automatically.

``` JavaScript
const stringIntegerNumber = "45"
const stringFloatNumber = "45.1"

// output -> 45 (is not a string anymore)
const int = Number(stringIntegerNumber)

// output -> 45.1 (is not a string anymore, and it is float)
const float = Number(stringFloatNumber)
```

## Unary operator (+)
Maybe in this selection of methods to transform a string into a number. This is definitely the weirdest, since isn't actually a JavaScript method or class but, instead a special operator.

As Number( ), the unary operator does the same functionality, but it has better performance if the people you work with have never read JavaScript's documentation this way can be not enough legible.

``` JavaScript
const stringIntegerNumber = "45"
const stringFloatNumber = "45.1"

// output -> 45 (is not a string anymore)
const int = +stringIntegerNumber

// output -> 45.1 (is not a string anymore, and it is float)
const float = +stringFloatNumber
```

If you don't understand what's going on let me tell you that this method works by adding a "+" operator immediately before a string with a numeric value (if there are spaces between "+" is considered the classic sum operator)

### If you have more methods you feel free to comment on them.
Typescript Union Keys And Make Uncommon Keys Optional
Tags: webdev, programming, typescript, tutorial
Published: 2022-08-07 22:24:00

```ts
type A = {name: string}
type B = {name: number}
type C = {name: string , age:number}
type D = {name: string , age:string}
type E = {name: string , address:string}

type Prettify<T extends Record<string, unknown>> = { [K in keyof T]: T[K] }

type UnionKeysAndMakeUncommonKeysOptional<
	T extends Record<string, unknown>[],
	ACC extends Record<string, unknown>={},
	UncommonKeyACC extends string = never
> = T extends []
	? Prettify<Omit<ACC, UncommonKeyACC> & Partial<Pick<ACC, UncommonKeyACC>>>
	: T extends [infer R, ...infer S extends Record<string, unknown>[]]
	? UnionKeysAndMakeUncommonKeysOptional<
			S,
			{ [K in keyof R | keyof ACC]: R[K & keyof R] | ACC[K & keyof ACC] },
			Exclude<keyof ACC | keyof R, keyof ACC & keyof R> & string
	  >
	: never


type result = UnionKeysAndMakeUncommonKeysOptional<[A,B,C,D,E]>
// {
//     name: string | number;
//     age?: string | number;
//     address?: string;
// }
```

[playground](https://www.typescriptlang.org/play?exactOptionalPropertyTypes=true&fbclid=IwAR0Nb1LrB_PJsIsdSGGB2uU4ob-BCPsBKb5Fj5tfiO-u7PFEATa8D3q2yD8#code/C4TwDgpgBAglC8UDeA7AhgWwgLigZ2ACcBLFAcwF8AoUSKAIQWXS1xQFcMAjCQ626AGEmqTDnxFSZKABooaMjg7de1GuGgAFQhGDBiAMxAAeACpQIAD2AQUAEzxQAShADGAe0J3jBEuTnsKADWKO4A7igAfJEiUADaANJQpFBBECDuBlCmALq4pok5UGoCUACqKMTuKILuGBjVMPYAsmhpFR711QDyYPrVaAA2xlQAkOZWNvaOLh5ePpL+UIEh4VFxOTJjMILCk7YOzm6e3r5SAcGhEZHwSBRbox11DSgJ6Tt71geOZ+RMKBAAG68KgxRATL7TeI5MYAfig2l0+iMxm6GGIwGMHzkTy6r3euxiADIEWhCPohsZNMRXEEsbscShOi83iAPtFImN8hZIYc4qQDLxnHIAHRigVCgDKPKmh1mJwWfjIF1W1w2MNG8IqVRqz0aLTaEFxL16-XQwzGo1GkoeVqQ8SSKTSGSyTigAB9UulMrBdnlnIkoCTnT6nEVPR9A8HvVkPkV7pbRgBRSyuQbsOwQYwh2O7D1el3Cgs+j5B4uu4kSJVjKBQTmjNhAkFUdR0HR4diDYBMbXVWp4pp2VrtJl6lCmnWUuIwGT0GSCHKcgD0S9rtYAerCgA)

require TS 4.7 and set `exactOptionalPropertyTypes` to true
Deploy a NodeJS Restful application with Docker using Nginx as the proxy-server( Ubuntu )
Tags: docker, node, nginx, ubuntu
Published: 2022-08-07 21:30:00

Lately, as a move towards efficient continuous integration and continuous development( CI/CD ), I have been dockerizing all my applications and running these applications inside containers using `Docker`. NodeJS turned out to be a hard nut to crack...but alas it's finally cracked. This is how i managed to dockerize and run a NodeJS RESTFUL app at long last.
1. Navigate to your preferred file system and create a directory and then change into the created directory.
`$ mkdir <foldername> && cd <foldername>`

2. Create a new nodejs app using `npm` or `yarn` by running: 
`$ npm init <application name>`
3. Add your app dependencies such as Express:
`$ npm install express --save` 
4. You should now have a `package.json` file, the `node_modules` folders and maybe some lock files. Create the main file this command under your app directory terminal window / shell by running: `$ touch <filename>.js`
5.Edit the `package.json` file. Add this if not existent under the scripts defintion and save the file.

```
"scripts": {
"start": "node <mainfile>"
}
```
6. To dockerize the app; add the following files from the terminal under the app directory file system.
`$ touch Dockerfile`
`$ touch docker-compose.yml`
7. Open and Edit the Dockerfile with the following contents.

```
# obtain the node image
FROM node
# change to the working directory
WORKDIR <directory_name>
#move the package file to the current working directory
COPY package*.json ./
# install the depedencies
RUN npm install
COPY . .
# run the app
CMD [ "node", <mainfile> ]
```

8. Make a new directory inside the app folder to handle the nginx configuration, cd into the folder and create a new nginx conf file.
`mkdir nginx && cd nginx && touch default.conf`
9. Edit the default conf file with these contents; `environment name` and `port` should be obtained and defined in the `docker-compose.yml` file.

```
http {
 upstream backend {
   server <environment_name: port>
 }
 server {
  location / {
    proxy_pass http://backend;
  } 
 }
}
```
10. Edit the `docker-compose.yml` with these contents.

```
versions: '3',
services:
  nginx_server:
    image: nginx #image of the nginx
    volumes: 
     - './nginx/default.conf:/etc/nginx/nginx.conf'
    ports:
     - '8000:80'
  #define the node app container
  app:
   container_name: <container name>
   build:
    context: .
    dockerfile: Dockerfile #name of the dockerfile we created
  ports:
   - '3000:80' #docker container port = 3000, host port= 80
  environment:
   - APPID=3000
```
Typescript WTF Moments 2: keyof {[x:string]:string} is string | number
Tags: webdev, programming, tutorial, typescript
Published: 2022-08-07 21:28:00

---
series: Typescript WTF Moments 
---

```ts
type A = {[x:string]:string} 
type B = keyof A // string | number
//   ^?

const A:A = {a:"abc",[1]:"xyz"}

type C = keyof A & string // string
//   ^?
```

[playground](https://www.typescriptlang.org/play?#code/C4TwDgpgBAglC8UDeBtAHgLgM7AE4EsA7AcwF1s8jiBfKAKFEigCEEoBrCEAewDNYoAekFQcBElAA+UQgFcAtgCMIuOsKgaAegH46dAMbdCOWBjiIkAQwwAiS4v02ANCgCM5G2hAAvG9T2M0ADCbJw8-HAAZKKUEupiVGoiWtpAA)

normally this will not cause any issue, because number key in javascript will coerce into string key

however this may cause issue if we are doing some type manipulation

to solve this we can intersect it with string or set 		`keyofStringsOnly` to true in the ts config

or just use `Record<string, T>` or `{[x in string]: T}`

**this is work as expected**

more on [github PR](https://github.com/microsoft/TypeScript/pull/23592) and [release note](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html#support-number-and-symbol-named-properties-with-keyof-and-mapped-types)
Typescript WTF Moments 1: Mixing String Literal Key And String Key In Object Literal Type
Tags: webdev, tutorial, programming, typescript
Published: 2022-08-07 21:11:00

---
series: Typescript WTF Moments
---

**This series is about confusions I encountered in Typescript, thing that is not intuitive, hard to reason with or require extra attention.** 

**The cause of caveats may be due to bug or deficiency or just simply work as intended**

**I will add new posts to this series from time to time.**

because Typescript has no [negate type](https://github.com/microsoft/TypeScript/pull/29317) and without it, `string` cannot cover key that are not `a1` and `a2`, `string` has to cover all keys.

```ts
type A = {[x:string]:1, a1:1, a2:2} // error: Property 'a2' of type '2' is not assignable to 'string' index type '1'.

type a = A['something'] // 1
//   ^?
type a1 = A['a1'] // 1
//   ^?
type a2 = A['a2'] // 2
//   ^?

const A:A={something:1, a1:1, a2:2} // error: Type '2' is not assignable to type '1'.

A.a2 = 2 // individual member write is ok
```

so far so good, Typescript error suggestion prevent us from doing it in the wrong way

However there is a case it will by pass the first error, that is using intersection

```ts
type B = {[x:string]:1} & { b1:1, b2:2} // no error

type b = B['something']
//   ^?
type b1 = B['b1']
//   ^?
type b2 = B['b2']
//   ^?

const B:B={something:1, b1:1, b2:2} // error: Type '2' is not assignable to type '1'.

B.b2 = 2 // individual member write is ok
```
[playground](https://www.typescriptlang.org/play?#code/C4TwDgpgBAglC8UDeBtAHgLgM7AE4EsA7AcwF0MBGAGigEMLKbaAmDZgXygHouoJdcAe1wYoABSGRcoKAHIWsqIIBmUUJDnNF+LFEKDgdLFnzFCtAEYAbaMEFycBEtsIATCGjXhosirIB0AFCB6tC0CLAosliCALYQwAAWRMSypNy8FIE8ULkAegD8Id50FBEwUfRpGVBZOflFoXTM5ZVa6TnM2bwNwQDGgoQ4sBgw8Egx8UkpjKWzLGycOfxCIlAAKiWyWlA6egZGJmaWNmr2Tb4BwTD+LBEtOUSu+ABu+K4ArrRWUPGxFvwoAB3AjAaB7QQAa2CTQAQhFUJhHClyBROAAyZBQCwMajY1gcGr6PgCYQwkoWCKwqKTBLJZykbq5KCFYoaHFUqI4tJM3pNCwtRDU2QCnn1FlFQIDIaGWEYWHjWnTEizHGqglLXgrYSiTYabbaXT6Qy0YymczWWznLZ+IKBWH+AX3GpPV7vL4-P4A3DA0Hg3RQoA)

The type is correct when you read it but not when you write it, individual write however is fine
Simplest way to monitor visits on your website (No Purchase, No Sign Up)
Tags: analytics, webdev, html, tutorial
Published: 2022-08-07 21:03:54

**Yes**, you don't have to purchase an Analytics Service or sign up to some sketchy application just to know simple thing like how many visits did your site has. Just with a few lines of code you can easily find out the overall visit count of your website.

##2 Steps to install this service

###Step 1: Add the following JavaScript to your Website ⚙️
Add the following code to your website where it is called every time a user visits (Could be your homepage). Replace [YOUR WEBSITE NAME] to your Website name or any other uniquely identifiable string
```
window.onload = function (){
    fetch('https://api.countapi.xyz/hit/[YOUR WEBSITE NAME]/visits')
}
```

###Step 2: View the Page Visits 🕵
To get the page view you can visit the following endpoint
```
https://api.countapi.xyz/get/[YOUR WEBSITE NAME]/visits
```

###Wait✋! but it might not be end for you
The example that I have provided is the bare minimum setup you need to do to monitor the visits. You might want to monitor the visits on each page of your site separately or want to have rather complex analytics. Thanks to [CountAPI](https://countapi.xyz/) which gives us this tooling for free. For more complex 'Visit Analytics', please go ahead and read the docs from [CountAPI](https://countapi.xyz/)

###Liked the solution?
If you liked the post you can read more from me. For more please follow me on my social media handles provided below

Blog👉 https://hariscodes.com/
Twitter👉 https://twitter.com/tweetharisahmad
Instagram👉 https://www.instagram.com/hariscodes/
Arrays
Tags: arrays, cpp
Published: 2022-08-07 20:11:23

_**Simple code to show how the Accessing and Modifying of array elements is done:**_

// AccessingAndModifyingArrayElements.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include "pch.h"
#include <iostream>
using namespace std;

int main()
{
    //std::cout << "Hello World!\n";

	//1. Accessing array elements
	cout << "1. Accessing array elements : " << endl;
	int arr[]{ 100, 20, 30, 50, 60 };

	cout << "Array element 1: " << arr[0] << endl;
	cout << "Array element 2: " << arr[1] << endl;
	cout << "Array element 3: " << arr[2] << endl;
	cout << "Array element 4: " << arr[3] << endl;
	cout << "Array element 5: " << arr[4] << endl;

	//2. Arrays are not check for out of bounds :
	// Most probably code will crash in such situations.
	//cout << "enter any number for arr[5] : " << endl;

	//cin >> arr[5];

	//3. Initializing array:
	cout << "\n";
	cout << "===============" << endl;
	cout << "\n";
	//int arr1[5];
	//int arr2[5]{};
	int arr3[5]{100, 90};

	cout << "Array element 1: " << arr3[0] << endl;
	cout << "Array element 2: " << arr3[1] << endl;
	cout << "Array element 3: " << arr3[2] << endl;
	cout << "Array element 4: " << arr3[3] << endl;
	cout << "Array element 5: " << arr3[4] << endl;

	//4. Modifying array elements
	cout << "Enter 5 nums for arr3 : ";
	cin >> arr3[0];
	cin >> arr3[1];
	cin >> arr3[2];
	cin >> arr3[3];
	cin >> arr3[4];

	cout << "MOdified array : " << endl;
	cout << arr3[0] << endl;
	cout << arr3[1] << endl;
	cout << arr3[2] << endl;
	cout << arr3[3] << endl;
	cout << arr3[4] << endl;

	cout << "the value of array name is : " << arr3 << endl;  // this shows the address value of 1st element of array.

	return 0;

}

Output:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i30ymniolrajqsvqymjt.PNG)
Reduct Storage Client SDK for C++ 0.7.0 was released
Tags: news, cpp, opensource, reductstorage
Published: 2022-08-07 19:46:00

This is a little update for people who follow news about Reduct Storage and its ecosystem.

I've just released a [new version](https://github.com/reduct-storage/reduct-cpp/releases/tag/v0.7.0) of the SDK which supports [HTTP API v0.7](https://docs.reduct-storage.dev/).
The most important new feature is the `IBucket::Query` method. It allows to iterate records for a given time interval:

```cpp
using reduct::IBucket;
using reduct::IClient;

int main() {
  auto client = IClient::Build("https://play.reduct-storage.dev");
  // Create a bucket
  auto [bucket, create_err] = client->GetOrCreateBucket("bucket");
  if (create_err) {
    std::cerr << "Error: " << create_err;
    return -1;
  }

  
  // Walk through the data
  err = bucket->Query("entry-1", std::nullopt, IBucket::Time::clock::now(), std::nullopt, [](auto&& record) {
    std::string blob;
    auto read_err = record.Read([&blob](auto chunk) {
      blob.append(chunk);
      return true;
    });

    if (!read_err) {
      std::cout << "Read blob: " << blob;
    }

    return true;
  });
}
```

You can use the library with CMake's `FetchContet` macros or install it from the source:

```
git clone https://github.com/reduct-storage/reduct-cpp.git
cd reduct-cpp
mkdir build && cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
cmake --build .
sudo cmake --build . --target install
```

In your CMakeLists.txt:

```cmake
find_package(ReductCpp 0.8.0)
find_package(ZLIB)
find_package(OpenSSL)

add_executable(you_app you_app.cc)
target_link_libraries(you_app ${REDUCT_CPP_LIBRARIES} ${ZLIB_LIBRARIES} OpenSSL::SSL OpenSSL::Crypto)
```

For more information, read [here](https://reduct-cpp.readthedocs.io/en/latest/)
Day 120: The lazy week is over!
Published: 2022-08-07 19:45:08

Hi!
The lazy week is over! whew!. This week had been an unusual one for me and so challenging to withstand I was so lazy and probably was not even as 1/3 productive as I usually am but fortunately it was not a complete waste I did few cool stuff reconnected with friends but still it feels good to finally put it to end. I'm currently super tired I won't be making a plan today I shall get to it maybe tomorrow morning 
I hope the next will be better.
See u there

Signing off...s
What's that thing you despise so much in software development?
Tags: discuss, webdev, programming, career
Published: 2022-08-07 19:42:58

I was gonna try make a post today but instead I'll rather listen today.

At various levels in our career we've come across some issues that pissed us of.

It could be having to explain every single line of code to a junior?
It could be dealing with version updates of dependencies,
It could be having to learn a new framework every 6 months lol.

So let's talk about it.
How to get current year in Next JS
Tags: nextjs, javascript
Published: 2022-08-07 18:16:13

Below code will help you to get full year in next JS.

```
function year() {
    const date = new Date();
    const year = date.getFullYear();
    return (
        <>
            <div>Current year is {year}</div>
        </>
  )
}

export default year;
```