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 */
first(): V {
return this.values().next().value
}
first(): V | undefined;
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 */
last(): V {
return [...this.values()][this.size - 1]
}
last(): V | undefined;
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 */
random(): V {
const arr = [...this.values()]
return arr[Math.floor(Math.random() * arr.length)]
}
random(): V;
random(amount: number): V[];
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(callback: (value: V, key: K) => boolean): V | undefined {