-
Notifications
You must be signed in to change notification settings - Fork 0
leetcode-2025-02-17 #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
max-zaitsev
wants to merge
1
commit into
main
Choose a base branch
from
2025-02-17
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1 @@ | ||
| # codewars-solutions | ||
| # Code problems solutions |
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| "use strict"; | ||
| // 2619. Array Prototype Last | ||
| // https://leetcode.com/problems/array-prototype-last/ | ||
| /** | ||
| * @return {null|boolean|number|string|Array|Object} | ||
| */ | ||
| Array.prototype.last = function () { | ||
| return this.length === 0 ? -1 : this.at(-1); | ||
| }; | ||
| /** | ||
| * const arr = [1, 2, 3]; | ||
| * arr.last(); // 3 | ||
| */ | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| // 2619. Array Prototype Last | ||
| // https://leetcode.com/problems/array-prototype-last/ | ||
|
|
||
| // Write code that enhances all arrays such that you can call the array.last() method on any array and it will return the last element. If there are no elements in the array, it should return -1. | ||
|
|
||
| // You may assume the array is the output of JSON.parse. | ||
|
|
||
| // Example 1: | ||
|
|
||
| // Input: nums = [null, {}, 3] | ||
| // Output: 3 | ||
| // Explanation: Calling nums.last() should return the last element: 3. | ||
| // Example 2: | ||
|
|
||
| // Input: nums = [] | ||
| // Output: -1 | ||
| // Explanation: Because there are no elements, return -1. | ||
|
|
||
| // Constraints: | ||
|
|
||
| // arr is a valid JSON array | ||
| // 0 <= arr.length <= 1000 | ||
|
|
||
| interface Array<T> { | ||
| last(): T; | ||
| } | ||
|
|
||
| /** | ||
| * @return {null|boolean|number|string|Array|Object} | ||
| */ | ||
| Array.prototype.last = function <T>() { | ||
| return this.length === 0 ? -1 : this.at(-1); | ||
| }; | ||
|
|
||
| /** | ||
| * const arr = [1, 2, 3]; | ||
| * arr.last(); // 3 | ||
| */ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| "use strict"; | ||
| // Write a class that allows getting and setting key-value pairs, however a time until expiration is associated with each key. | ||
| // The class has three public methods: | ||
| // set(key, value, duration): accepts an integer key, an integer value, and a duration in milliseconds. Once the duration has elapsed, the key should be inaccessible. The method should return true if the same un-expired key already exists and false otherwise. Both the value and duration should be overwritten if the key already exists. | ||
| // get(key): if an un-expired key exists, it should return the associated value. Otherwise it should return -1. | ||
| // count(): returns the count of un-expired keys. | ||
| class TimeLimitedCache { | ||
| cache = {}; | ||
| /** | ||
| * @param {number} key | ||
| * @param {number} value | ||
| * @param {number} duration time until expiration in ms | ||
| * @return {boolean} if un-expired key already existed | ||
| */ | ||
| set(key, value, duration) { | ||
| const currentTime = new Date().getTime(); | ||
| let oldNotExpired = false; | ||
| if (this.cache[key] && this.cache[key].expiresAt > currentTime) | ||
| oldNotExpired = true; | ||
| this.cache[key] = { value, expiresAt: currentTime + duration }; | ||
| return oldNotExpired; | ||
| } | ||
| /** | ||
| * @param {number} key | ||
| * @return {number} value associated with key | ||
| */ | ||
| get(key) { | ||
| const currentTime = new Date().getTime(); | ||
| if (this.cache[key] && this.cache[key].expiresAt > currentTime) | ||
| return this.cache[key].value; | ||
| return -1; | ||
| } | ||
| /** | ||
| * @return {number} count of non-expired keys | ||
| */ | ||
| count() { | ||
| return Object.entries(this.cache).reduce((acc, [key, value]) => { | ||
| if (value.expiresAt > new Date().getTime()) | ||
| acc += 1; | ||
| return acc; | ||
| }, 0); | ||
| } | ||
| } | ||
| /** | ||
| * const timeLimitedCache = new TimeLimitedCache() | ||
| * timeLimitedCache.set(1, 42, 1000); // false | ||
| * timeLimitedCache.get(1) // 42 | ||
| * timeLimitedCache.count() // 1 | ||
| */ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| // Write a class that allows getting and setting key-value pairs, however a time until expiration is associated with each key. | ||
|
|
||
| // The class has three public methods: | ||
|
|
||
| // set(key, value, duration): accepts an integer key, an integer value, and a duration in milliseconds. Once the duration has elapsed, the key should be inaccessible. The method should return true if the same un-expired key already exists and false otherwise. Both the value and duration should be overwritten if the key already exists. | ||
|
|
||
| // get(key): if an un-expired key exists, it should return the associated value. Otherwise it should return -1. | ||
|
|
||
| // count(): returns the count of un-expired keys. | ||
|
|
||
| class TimeLimitedCache { | ||
| private cache: Record<number, { value: number; expiresAt: number }> = {}; | ||
|
|
||
| /** | ||
| * @param {number} key | ||
| * @param {number} value | ||
| * @param {number} duration time until expiration in ms | ||
| * @return {boolean} if un-expired key already existed | ||
| */ | ||
| set(key: number, value: number, duration: number): boolean { | ||
| const currentTime = new Date().getTime(); | ||
| let oldNotExpired = false; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Всегда когда вижу let, начит проблема с функциональностью кода. Мои изменения cache - сменить на Мапу Добавить метод, для удаления истекших ключей |
||
| if (this.cache[key] && this.cache[key].expiresAt > currentTime) oldNotExpired = true; | ||
| this.cache[key] = { value, expiresAt: currentTime + duration }; | ||
| return oldNotExpired; | ||
| } | ||
|
|
||
| /** | ||
| * @param {number} key | ||
| * @return {number} value associated with key | ||
| */ | ||
| get(key: number): number { | ||
| const currentTime = new Date().getTime(); | ||
| if (this.cache[key] && this.cache[key].expiresAt > currentTime) return this.cache[key].value; | ||
| return -1; | ||
| } | ||
|
|
||
| /** | ||
| * @return {number} count of non-expired keys | ||
| */ | ||
| count(): number { | ||
| return Object.entries(this.cache).reduce<number>((acc, [key, value]) => { | ||
| if (value.expiresAt > new Date().getTime()) acc += 1; | ||
| return acc; | ||
| }, 0); | ||
| } | ||
| } | ||
| /** | ||
| * const timeLimitedCache = new TimeLimitedCache() | ||
| * timeLimitedCache.set(1, 42, 1000); // false | ||
| * timeLimitedCache.get(1) // 42 | ||
| * timeLimitedCache.count() // 1 | ||
| */ | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| "use strict"; | ||
| // 2693. Call Function with Custom Context | ||
| // https://leetcode.com/problems/call-function-with-custom-context/description/ | ||
| // Enhance all functions to have the callPolyfill method. The method accepts an object obj as its first parameter and any number of additional arguments. The obj becomes the this context for the function. The additional arguments are passed to the function (that the callPolyfill method belongs on). | ||
| // For example if you had the function: | ||
| // function tax(price, taxRate) { | ||
| // const totalCost = price * (1 + taxRate); | ||
| // console.log(`The cost of ${this.item} is ${totalCost}`); | ||
| // } | ||
| // Calling this function like tax(10, 0.1) will log "The cost of undefined is 11". This is because the this context was not defined. | ||
| // However, calling the function like tax.callPolyfill({item: "salad"}, 10, 0.1) will log "The cost of salad is 11". The this context was appropriately set, and the function logged an appropriate output. | ||
| // Please solve this without using the built-in Function.call method. | ||
| /** | ||
| * @param {Object} context | ||
| * @param {Array} args | ||
| * @return {null|boolean|number|string|Array|Object} | ||
| */ | ||
| // В целом, решение подходит под условие, но конечно читерское) Посмотрел потом правильное решение через прототипы и понял, что это ужас) | ||
| //@ts-ignore - тут ошибка из-за назначения нового свойства, когда его быть не должно в типе. Не понимаю, как решить (?) | ||
| Function.prototype.callPolyfill = function (context, ...args) { | ||
| return this.apply(context, [this, ...args]); | ||
| }; | ||
| /** | ||
| * function increment() { this.count++; return this.count; } | ||
| * increment.callPolyfill({count: 1}); // 2 | ||
| */ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| // 2693. Call Function with Custom Context | ||
| // https://leetcode.com/problems/call-function-with-custom-context/description/ | ||
|
|
||
| // Enhance all functions to have the callPolyfill method. The method accepts an object obj as its first parameter and any number of additional arguments. The obj becomes the this context for the function. The additional arguments are passed to the function (that the callPolyfill method belongs on). | ||
|
|
||
| // For example if you had the function: | ||
|
|
||
| // function tax(price, taxRate) { | ||
| // const totalCost = price * (1 + taxRate); | ||
| // console.log(`The cost of ${this.item} is ${totalCost}`); | ||
| // } | ||
| // Calling this function like tax(10, 0.1) will log "The cost of undefined is 11". This is because the this context was not defined. | ||
|
|
||
| // However, calling the function like tax.callPolyfill({item: "salad"}, 10, 0.1) will log "The cost of salad is 11". The this context was appropriately set, and the function logged an appropriate output. | ||
|
|
||
| // Please solve this without using the built-in Function.call method. | ||
|
|
||
| /** | ||
| * @param {Object} context | ||
| * @param {Array} args | ||
| * @return {null|boolean|number|string|Array|Object} | ||
| */ | ||
|
|
||
| // В целом, решение подходит под условие, но конечно читерское) Посмотрел потом правильное решение через прототипы и понял, что это ужас) | ||
|
|
||
| //@ts-ignore - тут ошибка из-за назначения нового свойства, когда его быть не должно в типе. Не понимаю, как решить (?) | ||
| Function.prototype.callPolyfill = function (context: Object, ...args: any[]) { | ||
| return this.apply(context, [this, ...args]); | ||
| }; | ||
|
|
||
| /** | ||
| * function increment() { this.count++; return this.count; } | ||
| * increment.callPolyfill({count: 1}); // 2 | ||
| */ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| "use strict"; | ||
| // // Given a function fn and a time in milliseconds t, return a debounced version of that function. | ||
| // // A debounced function is a function whose execution is delayed by t milliseconds and whose execution is cancelled if it is called again within that window of time. The debounced function should also receive the passed parameters. | ||
| // // For example, let's say t = 50ms, and the function was called at 30ms, 60ms, and 100ms. | ||
| // // The first 2 function calls would be cancelled, and the 3rd function call would be executed at 150ms. | ||
| // // If instead t = 35ms, The 1st call would be cancelled, the 2nd would be executed at 95ms, and the 3rd would be executed at 135ms. | ||
| // Constraints: 0 <= t <= 1000; | ||
| // 1 <= calls.length <= 10; | ||
| // 0 <= calls[i].t <= 1000; | ||
| // 0 <= calls[i].inputs.length <= 10; | ||
| /** | ||
| * @param {Function} fn | ||
| * @param {number} t milliseconds | ||
| * @return {Function} | ||
| */ | ||
| var debounce = function (fn, t) { | ||
| let timeout; | ||
| return function (...args) { | ||
| clearTimeout(timeout); | ||
| timeout = setTimeout(() => { | ||
| fn(...args); | ||
| }, t); | ||
| }; | ||
| }; | ||
| /** | ||
| * const log = debounce(console.log, 100); | ||
| * log('Hello'); // cancelled | ||
| * log('Hello'); // cancelled | ||
| * log('Hello'); // Logged at t=100ms | ||
| */ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| // // Given a function fn and a time in milliseconds t, return a debounced version of that function. | ||
|
|
||
| // // A debounced function is a function whose execution is delayed by t milliseconds and whose execution is cancelled if it is called again within that window of time. The debounced function should also receive the passed parameters. | ||
|
|
||
| // // For example, let's say t = 50ms, and the function was called at 30ms, 60ms, and 100ms. | ||
|
|
||
| // // The first 2 function calls would be cancelled, and the 3rd function call would be executed at 150ms. | ||
|
|
||
| // // If instead t = 35ms, The 1st call would be cancelled, the 2nd would be executed at 95ms, and the 3rd would be executed at 135ms. | ||
| // Constraints: 0 <= t <= 1000; | ||
| // 1 <= calls.length <= 10; | ||
| // 0 <= calls[i].t <= 1000; | ||
| // 0 <= calls[i].inputs.length <= 10; | ||
|
|
||
| /** | ||
| * @param {Function} fn | ||
| * @param {number} t milliseconds | ||
| * @return {Function} | ||
| */ | ||
|
|
||
| var debounce = function <T>(fn: (...args: Array<T>) => unknown, t: number): (...args: Array<T>) => void { | ||
| let timeout: ReturnType<typeof setTimeout>; | ||
| return function (...args: any[]) { | ||
| clearTimeout(timeout); | ||
| timeout = setTimeout(() => { | ||
| fn(...args); | ||
| }, t); | ||
| }; | ||
| }; | ||
|
|
||
| /** | ||
| * const log = debounce(console.log, 100); | ||
| * log('Hello'); // cancelled | ||
| * log('Hello'); // cancelled | ||
| * log('Hello'); // Logged at t=100ms | ||
| */ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| "use strict"; | ||
| // 2694. Event Emitter | ||
| // https://leetcode.com/problems/event-emitter/description/ | ||
| // Design an EventEmitter class. This interface is similar (but with some differences) to the one found in Node.js or the Event Target interface of the DOM. The EventEmitter should allow for subscribing to events and emitting them. | ||
| // Your EventEmitter class should have the following two methods: | ||
| // subscribe - This method takes in two arguments: the name of an event as a string and a callback function. This callback function will later be called when the event is emitted. | ||
| // An event should be able to have multiple listeners for the same event. When emitting an event with multiple callbacks, each should be called in the order in which they were subscribed. An array of results should be returned. You can assume no callbacks passed to subscribe are referentially identical. | ||
| // The subscribe method should also return an object with an unsubscribe method that enables the user to unsubscribe. When it is called, the callback should be removed from the list of subscriptions and undefined should be returned. | ||
| // emit - This method takes in two arguments: the name of an event as a string and an optional array of arguments that will be passed to the callback(s). If there are no callbacks subscribed to the given event, return an empty array. Otherwise, return an array of the results of all callback calls in the order they were subscribed. | ||
| class EventEmitter { | ||
| eventsCallbacksMap = new Map(); | ||
| /** | ||
| * @param {string} eventName | ||
| * @param {Function} callback | ||
| * @return {Object} | ||
| */ | ||
| subscribe(eventName, callback) { | ||
| const eventCallbacks = this.eventsCallbacksMap.get(eventName); | ||
| if (!eventCallbacks?.length) | ||
| this.eventsCallbacksMap.set(eventName, [callback]); | ||
| else | ||
| eventCallbacks.push(callback); | ||
| return { | ||
| unsubscribe: () => { | ||
| const eventCallbacks = this.eventsCallbacksMap.get(eventName); | ||
| if (!eventCallbacks) | ||
| return; | ||
| const filteredEventCallbacks = eventCallbacks.filter((_callback) => _callback !== callback); | ||
| this.eventsCallbacksMap.set(eventName, filteredEventCallbacks); | ||
| }, | ||
| }; | ||
| } | ||
| /** | ||
| * @param {string} eventName | ||
| * @param {Array} args | ||
| * @return {Array} | ||
| */ | ||
| emit(eventName, args = []) { | ||
| const eventCallbacks = this.eventsCallbacksMap.get(eventName); | ||
| if (!eventCallbacks?.length) | ||
| return []; | ||
| return eventCallbacks.map((callback) => callback(...args)); | ||
| } | ||
| } | ||
| /** | ||
| * const emitter = new EventEmitter(); | ||
| * | ||
| * // Subscribe to the onClick event with onClickCallback | ||
| * function onClickCallback() { return 99 } | ||
| * const sub = emitter.subscribe('onClick', onClickCallback); | ||
| * | ||
| * emitter.emit('onClick'); // [99] | ||
| * sub.unsubscribe(); // undefined | ||
| * emitter.emit('onClick'); // [] | ||
| */ |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
.at главное чтоб поддерживался ))