Skip to main content

Coderator Follow System CRUD

1 like • Nov 18, 2022 • 3 views
TypeScript
Loading...

More TypeScript Posts

React usePrevious Hook

0 likes • Oct 15, 2022 • 40 views
TypeScript
import { useState, useEffect, useRef } from "react";
// Usage
function App() {
// State value and setter for our example
const [count, setCount] = useState(0);
// Get the previous value (was passed into hook on last render)
const prevCount = usePrevious(count);
// Display both current and previous count value
return (
<div>
<h1>
Now: {count}, before: {prevCount}
</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
// Hook
function usePrevious(value) {
// The ref object is a generic container whose current property is mutable ...
// ... and can hold any value, similar to an instance property on a class
const ref = useRef();
// Store current value in ref
useEffect(() => {
ref.current = value;
}, [value]); // Only re-run if value changes
// Return previous value (happens before update in useEffect above)
return ref.current;
}

langToConfig map

0 likes • Mar 31, 2023 • 2 views
TypeScript
const langToConfig = {
'javascript': {
image: '',
cmd: ['']
},
'php': {
image: '',
cmd: ['']
},
}

typescript hello

0 likes • Nov 21, 2023 • 19 views
TypeScript
// Print Hello, World!
console.log("Hello, World!");

retryPromise.ts

0 likes • Oct 20, 2023 • 5 views
TypeScript
//Retries maxRetries number of times, meaning that if you have 0, then it'll run the function once.
async function retryPromise<T>(
promiseFn: () => Promise<T>,
maxRetries = 3,
delayOffset = 0,
delayRandomRange = 0
): Promise<T> {
return new Promise<T>((resolve, reject) => {
promiseFn()
.then(resolve, (error: any) => { //On error
if (maxRetries <= 0) {
return reject(error);
} else {
if(delayRandomRange * Math.random() + delayOffset < 1.0){
return retryPromise(promiseFn, maxRetries - 1, delayOffset, delayRandomRange).then(resolve, reject);
}else{
return new Promise<T>((resolveTwo, rejectTwo) => {
setTimeout(() => {
return retryPromise(promiseFn, maxRetries - 1, delayOffset, delayRandomRange).then(resolveTwo, rejectTwo);
}, delayRandomRange * Math.random() + delayOffset);
}).then(resolve, reject);
}
}
});
});
}
//Returns a function that will fail numTimes times, then will return aValue
function functionThatReturnsAFunctionThatFailsACoupleTimes(numTimes: number, aValue: any): () => Promise<any> {
return async function(){
if(numTimes == 0){
return aValue;
}
numTimes--;
throw false;
};
}
const SMALL_NUMBER = 10;
function testTest(failNumberOfTimes: number){
let functionThatFailsACoupleTimes = functionThatReturnsAFunctionThatFailsACoupleTimes(failNumberOfTimes, true);
//Test my test
for(let i = 0; i < (failNumberOfTimes * 2); ++i){
function evalTest(val: any){
let testTestFailedReason = "";
if(val === undefined){
testTestFailedReason = "Test test returned undefined for some reason.";
}
if((i + 1) > failNumberOfTimes){
if(val === true){
//We're good
}else{
testTestFailedReason = "Test test didn't return true when it should have.";
}
}else{
if(val === false){
//We're good
}else{
testTestFailedReason = "Test test didn't return false when it should have.";
}
}
testTestFailedReason = testTestFailedReason || "Test test passed test case";
console.log(testTestFailedReason, "at index", i, "where the function returned", val);
}
functionThatFailsACoupleTimes().then(evalTest, evalTest)
};
}
testTest(SMALL_NUMBER);
let testCaseCounter = 1;
const throwsNoError = [
(val: any) => {
if(val == true){
console.log("Passed test case " + testCaseCounter++);
}else{
console.error("Unexpected return value", val);
}
},
() => {
console.error("It wasn't supposed to fail!")
}
]
const throwsError = [
(val: any) => {
console.error("It wasn't supposed to succeed!", val);
},
(val: any) => {
if(val == false){
console.log("Passed test case " + testCaseCounter++);
}else{
console.error("Unexpected return value", val);
}
}
];
//Runs SMALL_NUMBER times, because SMALL_NUMBER - 1 is the number of retries after the first one
let functionThatFailsACoupleTimes = functionThatReturnsAFunctionThatFailsACoupleTimes(SMALL_NUMBER - 1, true);
retryPromise(functionThatFailsACoupleTimes, SMALL_NUMBER - 1).then(...throwsNoError)
functionThatFailsACoupleTimes = functionThatReturnsAFunctionThatFailsACoupleTimes(SMALL_NUMBER - 1, true);
//Runs SMALL_NUMBER - 1 times, because SMALL_NUMBER - 2 is the number of retries after the first one
retryPromise(functionThatFailsACoupleTimes, SMALL_NUMBER - 2).then(...throwsError)
//Testing the delay. You'll have to wait a bit too.
functionThatFailsACoupleTimes = functionThatReturnsAFunctionThatFailsACoupleTimes(SMALL_NUMBER - 1, true);
//Runs SMALL_NUMBER times, because SMALL_NUMBER - 1 is the number of retries after the first one
retryPromise(functionThatFailsACoupleTimes, SMALL_NUMBER - 1, 500, 500).then(...throwsNoError)
functionThatFailsACoupleTimes = functionThatReturnsAFunctionThatFailsACoupleTimes(SMALL_NUMBER - 1, true);
//Runs SMALL_NUMBER - 1 times, because SMALL_NUMBER - 2 is the number of retries after the first one
retryPromise(functionThatFailsACoupleTimes, SMALL_NUMBER - 2, 500, 500).then(...throwsError)

class based task manager

0 likes • Jun 1, 2023 • 2 views
TypeScript
interface Task {
id: number;
title: string;
completed: boolean;
}
class TaskManager {
private tasks: Task[] = [];
constructor() {}
addTask(title: string) {
const taskId = this.tasks.length + 1;
const task: Task = {
id: taskId,
title,
completed: false,
};
this.tasks.push(task);
}
markTaskAsComplete(taskId: number) {
const task = this.tasks.find((task) => task.id === taskId);
if (task) {
task.completed = true;
}
}
markTaskAsIncomplete(taskId: number) {
const task = this.tasks.find((task) => task.id === taskId);
if (task) {
task.completed = false;
}
}
listTasks() {
console.log('Tasks:');
this.tasks.forEach((task) => {
console.log(`${task.id}. [${task.completed ? 'X' : ' '}] ${task.title}`);
});
}
}
// Example usage:
const taskManager = new TaskManager();
taskManager.addTask('Buy groceries');
taskManager.addTask('Pay bills');
taskManager.addTask('Clean the house');
taskManager.listTasks();
// Output:
// Tasks:
// 1. [ ] Buy groceries
// 2. [ ] Pay bills
// 3. [ ] Clean the house

Depth-First Search in TypeScript

0 likes • Oct 15, 2022 • 29 views
TypeScript
class DFS
{
public dfs(G: DFSGraph, startVert: number)
{
let visited: boolean[] = Array<boolean>();
// Pre-populate array:
for(let i = 0; i < G.size; i++)
{
visited.push(false);
}
let s: number[] = new Array();
visited[startVert] = true;
s.push(startVert);
while(s.length > 0)
{
const v = s.pop();
for(let adjV of G.adj[v])
{
if(!visited[adjV])
{
visited[adjV] = true;
s.push(adjV);
}
}
}
}
public dfsRecursive(G: DFSGraph, startVert: number)
{
let visited: boolean[] = Array<boolean>();
// Pre-populate array:
for(let i = 0; i < G.size; i++)
{
visited.push(false);
}
this.dfsAux(G, startVert, visited);
}
private dfsAux(G: DFSGraph, v: number, visited: boolean[])
{
visited[v] = true;
for(let adjV of G.adj[v])
{
if(!visited[adjV])
{
// this.foo(); // Something can happen before the visit.
this.dfsAux(G, adjV, visited);
// this.bar(); // Something can happen after the visit.
}
}
}
}