رقصنده با کد
782 subscribers
1.69K photos
850 videos
207 files
666 links
Here are some interesting things I've come across during my learning process. That's it. Admin ID:
@alithecodeguy
Download Telegram
Javascript - Day 16

Promisify

Before promises/async/await became the standard, it was a convention for async APIs in JavaScript to accept callbacks as the last argument. Many async versions of Node.js APIs (e.g. fs.readFile and fs.rm) have such signatures. Node.js' util.promisify function was created to wrap around callback-based functions by returning Promises so that they can be used with async/await.

Implement a function promisify that takes a function following the common callback-last error-first style, i.e. taking a (err, value) => ... callback as the last argument, and returns a version that returns promises.

Examples


// Example function with callback as last argument
// The callback has the signature `(err, value) => any`
function foo(url, options, callback) {
apiCall(url, options)
.then((data) => callback(null, data))
.catch((err) => callback(err));
}

const promisifiedFoo = promisify(foo);
const data = await promisifiedFoo('example.com', { foo: 1 });


@danceswithcode
@alithecodeguy

#js #javascript #interview87
Javascript - Day 17

Throttle

Throttling is a technique used to control how many times we allow a function to be executed over time. When a JavaScript function is said to be throttled with a wait time of X milliseconds, it can only be invoked at most once every X milliseconds. The callback is invoked immediately and cannot be invoked again for the rest of the wait duration.

Implement a throttle function which accepts a callback function and a wait duration. Calling throttle() returns a function which throttled invocations of the callback function following the behavior described above.

Examples


let i = 0;
function increment() {
i++;
}
const throttledIncrement = throttle(increment, 100);

// t = 0: Call throttledIncrement(). i is now 1.
throttledIncrement(); // i = 1

// t = 50: Call throttledIncrement() again.
// i is still 1 because 100ms have not passed.
throttledIncrement(); // i = 1

// t = 101: Call throttledIncrement() again. i is now 2.
// i can be incremented because it has been more than 100ms
// since the last throttledIncrement() call at t = 0.
throttledIncrement(); // i = 2


@danceswithcode
@alithecodeguy

#js #javascript #interview87
Javascript + React - Day 18

useArray

Implement a useArray hook that manages an array of items with additional utility methods.

It is more convenient to use useArray over plain useState because in the latter case, you would always have to create a new array, mutate it, then set state to use the new array, which can be quite cumbersome.

The hook should work generically with arrays of any types.


const defaultValue = ['apple', 'banana'];

export default function Component() {
const { array, push, update, remove, filter, set, clear } = useArray();

return (
<div>
<p>Fruits: {array.join(', ')}</p>
<button onClick={() => push('orange')}>Add orange</button>
<button onClick={() => update(1, 'grape')}>
Change second item to grape
</button>
<button onClick={() => remove(0)}>Remove first</button>
<button onClick={() => filter((fruit) => fruit.includes('a'))}>
Keep fruits containing 'a'
</button>
<button onClick={() => set(defaultValue)}>Reset</button>
<button onClick={clear}>Clear list</button>
</div>
);
}


Arguments

- defaultValue: The initial array of items

Returns

The hook returns an object with the following properties:

- array: The current array of items
- set: (newArray) => void: A function that sets the array of items. This must be the same type as the setter function of useState
- push: (item) => void: A function that adds an item to the end of the array
- remove: (index: number) => void: A function that removes an item from the array by index
- filter: (predicate) => void: A function that filters the array based on a predicate function. predicate must be the same type as the argument of Array.prototype.filter
- update: (index: number, newItem) => void: A function that replaces an item in the array at index
- clear: () => void: A function that clears the array

@danceswithcode
@alithecodeguy

#js #javascript #interview87
Javascript + React - Day 19

useDebounce

Implement a useDebounce hook that delays state updates until a specified delay has passed without any further changes to the provided value.


export default function Component() {
const [keyword, setKeyword] = useState('');
const debouncedKeyword = useDebounce(keyword, 1000);

return (
<div>
<input value={keyword} onChange={(e) => setKeyword(e.target.value)} />
<p>Debounced keyword: {debouncedKeyword}</p>
</div>
);
}


The observable outcome of using useDebounce is quite similar to React's useDeferredValue, the former returns an updated value after a fixed duration while the latter always returns the updated value but updates to the DOM relies on React's priority system.

Arguments

1. value: The value to debounce
2. delay: number: The delay in milliseconds

Returns

The hook returns the debounced value.

@danceswithcode
@alithecodeguy

#js #javascript #interview87
Javascript + React - Day 20

useSet

Implement a useSet hook that manages a JavaScript Set of items with additional utility methods.

It is more convenient to use useSet over plain useState because in the latter case, you would always have to create a new Set, mutate it, then set state to use the new set, which can be quite cumbersome.

The hook should work generically with items of any types.


export default function Component() {
const { set, add, remove, toggle, reset, clear } = useSet(new Set(['hello']));

return (
<div>
<button onClick={() => add(Date.now().toString())}>Add</button>
<button onClick={() => remove('hello')} disabled={!has('hello')}>
Remove 'hello'
</button>
<button onClick={() => toggle('hello')}>Toggle hello</button>
<button onClick={() => reset()}>Reset</button>
<button onClick={() => clear()}>Clear</button>
<pre>{JSON.stringify(Array.from(set), null, 2)}</pre>
</div>
);
}


Arguments

- initialState: The initial Set of items

Returns

The hook returns an object with the following properties:

- set: The current set of items
- add: (item) => void: A function that adds item to the set
- remove: (item) => void: A function that removes item from the set
- toggle: (item) => void: A function that toggles the presence of item in the set
- reset: () => void: A function that resets the set to initialState
- clear: () => void: A function that removes all items in the set

@danceswithcode
@alithecodeguy

#js #javascript #interview87