𝙐𝙣𝙧𝙚𝙖𝙡 𝘾𝙤𝙙𝙚𝙧
1.64K subscribers
6 photos
7 files
34 links
A place for coders ;)
Download Telegram
#js

Prototype Function to validate number

String.prototype.isdigit = () =>{
return /^\d+$/.test(this);
};

// Usage:
var string = "56";
console.log(string.isdigit()); // Output: true

var string2 = "hello123";
console.log(string2.isdigit()); // Output: false
#js

Make post and get request with headers in Plain js

async function request(url, method, dataType = "text", payload = {}, headers = {}) {
try {
const response = await fetch(url, {
method,
headers,
body: JSON.stringify(payload)
});

if (!response.ok) {
throw new Error(Request failed with status ${response.status});
}

if (dataType === "json") {
return await response.json();
} else {
return await response.text();
}
} catch (error) {
throw new Error("Request failed due to a network error");
}
}

// Usage example:
try {
const response = await request("https://api.example.com/data", "get", "json", {}, { "Authorization": "Bearer token" });
console.log(response);
} catch (error) {
console.error(error);
}


Using asynchronous we need async event to prevent pending promise.
#js
Request module to handle requests in js

class Request {
static async post(url, payload = {}, headers = {}) {
try {
const response = await fetch(url, {
method: "POST",
headers,
body: JSON.stringify(payload)
});

if (!response.ok) {
throw new Error(Request failed with status ${response.status});
}

return response;
} catch (error) {
throw new Error("Request failed due to a network error");
}
}

static async get(url, headers = {}) {
try {
const response = await fetch(url, {
method: "GET",
headers
});

if (!response.ok) {
throw new Error(Request failed with status ${response.status});
}

return response;
} catch (error) {
throw new Error("Request failed due to a network error");
}
}
}

// Usage example:
const url = "https://api.example.com/data";
const payload = { name: "John", age: 30 };
const headers = { "Authorization": "Bearer token" };

// POST request
Request.post(url, payload, headers)
.then(response => {
console.log(response.json());
})
.catch(error => {
console.error(error);
});

// GET request
Request.get(url, headers)
.then(response => {
console.log(response.json());
})
.catch(error => {
console.error(error);
});


Remember: if data does not return json response you need to set response.text() rather than response.json()
👍1
#js

Json Beautify Using Stringify

const data = { key1: 'value1', key2: 'value2' };
const jsonString = JSON.stringify(data, null, 2);


console.log(jsonString);
#bestPractice #php #js #py
Join an array into String in (PHP, JS, PY)

Bad practice:
//python
print("a" + " " + "b)

//php
echo "a"." ".b";

Best Practice:
// js
console.log(["a", "b"].join(" "));

//python
print(" ".join(["a", "b"])

//php
echo implode(" ", ["a", "b"]);
#js
Instant Execute Function in
js

// Normally:


(function() {
// Code to be executed immediately
})();

//Best Way Its called arrow function:

(() => {
// Code to be executed immediately
})();
👏2
#bestPractice #js
How to prevent Cannot read properties of undefined using ? operator

let user = { };

Noob coders:
if(user && user.name){
console.log(user.name);
}else{
console.log("No name found in user object")
}

Pro coders:
console.log(user?.name ?? "No name found in user Object")


Pro tips by Biswa
👍3😁2
How to merge 2 or many json dict into One in (Python, PHP, JS)

#js
var b = { success:true }
var c = { message: "something", ...b }
console.log(c)


Usage: Use "var" keyword to re assign the variable and use spread method to merge "...json object "

#php
$b = [ "success"=> true ];
$c = ["biswa":"string"];
array_merge($b, $c)

Usage: array_merge used to merge arrays into one array and we need use json_decode and json_encode to make a json obj

#py

Best way to merge in python is using unpacking operator **dict_name here is example:

b = { "success":True }
c = { "hell":None}
print({**b, **c})
😱7😢5🤮4💩4😁3🤬3👎2🤔2👍1🔥1🤯1