documentcloud / documentcloud/underscore-contrib
Change the treatment of falsy values in _.toQuery and _.fromQuery?
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 622
- Forks
- 114
- PR merge metrics
- No merged PRs in 30d
Description
@yashshah1 pointed out a problem with _.toQuery and _.fromQuery: through stringification, falsy values are being "upgraded" to truthy if you encode them and then decode them again. For example, _.fromQuery(_.toQuery({a: null})) returns {a: 'null'}.
@yashshah1 proposed the following solution in https://github.com/documentcloud/underscore-contrib/pull/229#issuecomment-683548408:
What I am suggesting is a change in both
toQueryandfromQuery.Proposed behaviour:
_.toQuery('{ a: '', b: null, c: undefined, d: '10' }') // a=&b=&d=10 _.fromQuery('a=&b=&d=10') // { a: '', b: '', d: '10' }Reasoning
The idea is that toQuery and fromQuery need to be as complementary to each other as possible, one drawback that's seen already is that numbers need to be re-parsed. Wrt falsy values, however, I think there has to be a special provision as described above.What we gain by this is that null values are re-encoded as empty strings, which is falsy, and undefined isn't included in the object, which leads to almost the same usage in a few cases.
var obj = { a: '', b: null, c: undefined, d: '10' } console.log(obj['c']) // undefined obj = _.fromQuery(_.toQuery(obj)) console.log(obj['c']) // undefinedThis might lead to a change in the behaviour of
fromQueryand I am happy to raise a PR should this be acceptable.
I'm not sure whether this approach would be the right solution, for a couple of reasons:
- Information loss:
undefined,nulland the empty string''could no longer be distinguished. - What to do with numeric zero?
- How does this align with jQuery's encoding conventions?
However, this is something we can discuss. Let's do that here.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the _.toQuery and _.fromQuery entry points and review the linked pull-request discussion. Decide how null, undefined, empty strings, and numeric zero should round-trip, including whether jQuery conventions apply. Done means an agreed behavior is documented and both functions have coverage for the selected cases.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript
- Domain
- web-dev
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100