Skip to content
This repository has been archived by the owner on Aug 9, 2024. It is now read-only.

RFC: createMap #17

Open
Kelin2025 opened this issue Jul 7, 2023 · 3 comments
Open

RFC: createMap #17

Kelin2025 opened this issue Jul 7, 2023 · 3 comments
Assignees
Labels
enhancement New feature or request

Comments

@Kelin2025
Copy link
Member

Case

Sometimes you need to calculate data for every record in KV

Worth mentioning:

  • Calculated data might be anything. E.g. it can be a sum of two fields, some string based on certain conditions. Literally anything. So API should be low-level rather than something rigid like createSwitch etc.

Solution

import { createListApi, createMapApi } from '@keyval/core'

type StatsWidgetState = {
  widgetId: string;
  ethValue: number;
  txPerDay: number
}

const $statsWidgets = createListApi<StatsWidgetState>({
  keygen: item => item.widgetId
})

const $roles = createMap($statsWidgets, {
  fn: stats => {
    if (stats.ethValue > 10) { return 'whale' }
    if (stats.txPerDay > 10) { return 'day_trader' }
    return 'stalling'
  }
})

Also, there's an optional source field

const $roles = createMap($statsWidget, {
  source: $preferredRole,
  fn: (stats, preferredRole) => {
    const roles = []
    /* calculate roles */
    if (roles.includes(preferredRole)) { return preferredRole }
    return roles[0] ?? 'stalling'
  }
})
@Kelin2025 Kelin2025 added the enhancement New feature or request label Jul 7, 2023
@Kelin2025 Kelin2025 self-assigned this Jul 7, 2023
@Minhir
Copy link
Member

Minhir commented Jul 8, 2023

There is could be a case where you don't need all your key-values. For example, you want to have only roles.includes(preferredRole) values in map. In such case, we can create filter api as well. Also, if your kv changes very often, filter could save a lot of updates.

Additionally, I can imagine the case with desired updates only triggered by clock.

createMap($statsWidgets, {
  clock,
  filter,
  fn
})

That thing looks very similar to sample. That could be a good reason to create sourcebale API for sample and use kv as source.

Anyway, I think it would be nice to have createMap with clock, filter and fn as first implementation.

@Minhir
Copy link
Member

Minhir commented Jul 8, 2023

Can we keep only one extended function for this?

createSelection(k$v, {source, filter, map})

@Minhir Minhir mentioned this issue Jul 8, 2023
@Kelin2025
Copy link
Member Author

Kelin2025 commented Jul 9, 2023

I think we can merge createSelection + createMap into one method if both fn and filter will be optional. Will you help with TS @Minhir?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants