sodiray / radash

Functional utility library - modern, simple, typed, powerful
https://radash-docs.vercel.app
MIT License
4.24k stars 169 forks source link

Fluent API #345

Open stefaanMLB opened 1 year ago

stefaanMLB commented 1 year ago

Would be nice to have a fluent API, f. i.

import { mapEntries } from 'radash/fluent'

const ra = {
  name: 'Ra',
  power: 'sun',
  rank: 100,
  culture: 'egypt'
}

ra.mapEntries((key, value) => [key.toUpperCase(), `${value}`]) 
// => { NAME: 'Ra', POWER: 'sun', RANK: '100', CULTURE: 'egypt' }
osdiab commented 1 year ago

how would this work? ra is a plain object and doesn't have a mapEntries member.

stefaanv commented 10 months ago

Can be done with this code. Example for the unique function

declare global {
  interface Array<T> {
    unique(toKey?: SelectFn<T>): Array<T>
  }
}

export interface Array<T> {
  unique(toKey?: SelectFn<T>): Array<T>
}

Array.prototype.unique = function <T>(toKey?: SelectFn<T>) {
  return unique(this, toKey)
}

The unique function can then be used like this:

const u = fish.unique(f => f.name)

Some people prefer this fluent type of API. It also aligns better with the built-in array functions.