Skip to content
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

syntax/support for dynamic paths #17

Open
acutmore opened this issue Jan 9, 2021 · 0 comments
Open

syntax/support for dynamic paths #17

acutmore opened this issue Jan 9, 2021 · 0 comments

Comments

@acutmore
Copy link

acutmore commented Jan 9, 2021

There are at least two situations where needing to specify the path literally can be frustrating:

Situation 1: Mutating deep path based on current value

player = #{
  ...player,
  // 'stats.medals.gold' repeated
  stats.medals.gold: player.stats.medals.gold + 1
}

Situation 2: writing utility function for updating a path

function increment(record, ...path) {
   // even a 'simple' implementation is ~10 lines before adding error checks
   assert(path.length > 0);
   let [prop, ...rest] = path;
   if (rest.length === 0) {
     return {
        ...record,
        [prop]: record[prop] + 1
     }
   }
   return {
     ...record,
     [prop]: increment(record[prop], ...rest)
   }
}

Idea: Add syntax for dynamic paths

If a value could be used as a path then it can be reused and passed around. An array of string/number keys could be used for such a value. Above examples become:

let path = ['stats', 'medals', 'gold'];
player = #{
  ...player,
  [...path]: player[...path] + 1
}
function increment(record, ...path) {
   assert(path.length > 0);
   return #{ ...record, [...path]: record[...path] + 1 }
}

Alternative: Add static helper

Alternatively this type of update could be added to the global Record object. Something like Record.update(record, path, update).

player = Record.update(player, ['stats', 'medals', 'gold'], val => val + 1);
function increment(record, ...path) {
   assert(path.length > 0);
   return Record.update(record, path, val => val + 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant