update collection methods

changes the methods like first(), last() and random()
This commit is contained in:
Snowflake 2020-12-14 13:14:14 +05:45 committed by GitHub
parent a9bee52d4c
commit 79437c8936
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -11,20 +11,37 @@ export class Collection<K = string, V = any> extends Map<K, V> {
} }
/** Get first value in Collection */ /** Get first value in Collection */
first(): V { first(): V | undefined;
return this.values().next().value first(amount: number): V[];
} first(amount?: number): V | V[] | undefined {
if (typeof amount === 'undefined') return this.values().next().value
if (amount < 0) return this.last(amount * -1)
amount = Math.min(this.size, amount)
const iter = this.values()
return Array.from({ length: amount }, (): V => iter.next().value)
}
/** Get last value in Collection */ /** Get last value in Collection */
last(): V { last(): V | undefined;
return [...this.values()][this.size - 1] last(amount: number): V[];
} last(amount?: number): V | V[] | undefined {
const arr = this.array()
if (typeof amount === 'undefined') return arr[arr.length - 1]
if (amount < 0) return this.first(amount * -1)
if (!amount) return []
return arr.slice(-amount)
}
/** Get a random value from Collection */ /** Get a random value from Collection */
random(): V { random(): V;
const arr = [...this.values()] random(amount: number): V[];
return arr[Math.floor(Math.random() * arr.length)] random(amount?: number): V | V[] {
} let arr = this.array()
if (typeof amount === 'undefined') return arr[Math.floor(Math.random() * arr.length)]
if (arr.length === 0 || !amount) return []
arr = arr.slice()
return Array.from({ length: amount }, (): V => arr.splice(Math.floor(Math.random() * arr.length), 1)[0])
}
/** Find a value from Collection using callback */ /** Find a value from Collection using callback */
find(callback: (value: V, key: K) => boolean): V | undefined { find(callback: (value: V, key: K) => boolean): V | undefined {