Proposal: Selector/Select Expression
I can appreciate the intent of the proposal. 👍
Minor nit with one of the examples:
// user[] => email[] (With Arrays)
const getEmailsList = users => users.map(user => user.contacts.email);
const getEmailsList = .map(.contacts.email);
I would think with the proposal you'd still need to reference `users`.
Otherwise what are we mapping?
const getEmailsList = users.map(.contacts.email);
This new notation will enable you a new way to create functions
.map(...)
produces (parameter) => parameter.map(...)
, it is not
evaluated, it is a function definition
I cannot say I like it. To me it is less readable, confusing to be exact.
Anything leading with .
(dot), seems unusual
---------- Původní e-mail ---------- Od: Scott Rudiger <scottrudiger at gmail.com>
Komu: Simon Farrugia <simonfarrugia26 at gmail.com>
Datum: 21. 6. 2019 15:30:53 Předmět: Re: Proposal: Selector/Select Expression "
I can appreciate the intent of the proposal. 👍
Minor nit with one of the examples:
// user[] => email[] (With Arrays)
const getEmailsList = users => users.map(user => user.contacts.email);
const getEmailsList = .map(.contacts.email);
I would think with the proposal you'd still need to reference `users`.
Otherwise what are we mapping?
const getEmailsList = users.map(.contacts.email);
On Fri, Jun 21, 2019, 4:49 AM Simon Farrugia <simonfarrugia26 at gmail.com
(mailto:simonfarrugia26 at gmail.com)> wrote:
"
Selector/Select Expression
Doing functional & reactive programming is currently really verbose in
JavaScript.
Hopefully this issue will be alleviated with the addition of the pipe
operator in the near future.
One things you end up doing most when doing fp is doing simple selections
(mappings) on objects & arrays. This unfortunately becomes really verbose
and repetitive.
What I'm proposing is to be able to collapse/simplify selector arrow
function expressions like this:
```
// user => email
const getEmail = user => user.contacts.email;
```
to something like this:
```
// user => email
const getEmail = .contacts.email;
```
More examples:
```
// user[] => email[] (With Arrays)
const getEmailsList = users => users.map(user => user.contacts.email);
const getEmailsList = .map(.contacts.email);
// Usage with pipeline operator
pipe(user, map(user => user.contacts.email))
user |> .contacts.email
```
I think this would work really well, particularly in conjunction with the
pipeline operator, resulting in more concise and expressive code improving
readability.
This is just syntactic sugar, but same as in the case of the pipeline
operator, selector functions are so intrinsic and commonplace to any code
base, that I would think it's worth considering.
I would appreciate hearing your thoughts. Thanks.
_______________________________________________
es-discuss mailing list
es-discuss at mozilla.org(mailto:es-discuss at mozilla.org)
https://mail.mozilla.org/listinfo/es-discuss
(https://mail.mozilla.org/listinfo/es-discuss)
"
_______________________________________________
es-discuss mailing list
es-discuss at mozilla.org
https://mail.mozilla.org/listinfo/es-discuss
"
Thanks for the feedback Scott,
Regarding your concern about the array example, both expressions are valid but different:
This (what you wrote) would map the array of users to an array of emails and declare getEmailsList as an array of emails.
const getEmailsList = users.map(.contacts.email);
While this (my array example) would define getEmailsList as a function that takes an array of users and returns an array of emails.
const getEmailsList = .map(.contacts.email);
Got it, that make sense.
I like the motivation behind the proposal. If it moves forward, I could see people possibly not liking (and bikeshedding) on the bare dot syntax, especially as it adds a new form of defining a function. Although, personally, I got used to it in less than a minute.
New syntax will always look a bit odd at first until we get used to it.
I sometimes find nested arrow functions a bit confusing to understand where one function starts and where it ends particularly when they are one liners. This syntax is more concise and personally I find it more readable.
Reasons for the leading dot notation is because I think it's intuitive and also self explanatory:
- We just remove what is in common on both ends of the expression (like simplifying an algebraic expression).
const getEmail = user => user.contacts.email;
- The leading dot indicates that the expression reads the property of an object that is not statically defined.
const getEmail = .contacts.email;
Personally, I'm a huge fan of this proposal. It would integrate into the
language the extremely frequent idiom of defining a pick/pluck like
function. There is ample prior art in the form of Ramda's pick function
ramdajs.com/docs/#pick.as well as pluck
in RxJS.
In fact, this exact proposal was at one point included in the proposal for "extended dot notation", then removed in the interests of making making it more digestible.
AFAICS the syntax is completely unambigious:
const pickName = .name; // equivalent to ({name}) => name
[{id: 1, name: "Bob"}, {id: 2, name: "Sally"}].map(pickName
The only objection I can think of is that the leading dot is sometimes hard to see. I would have suggested using the hash mark--in fact, an early version of the exptended dot notation proposal did propose that--but now that has been taken by the private fields proposal, so unless we want to go in the direction of keywords or magic operator sequences we are reduced to using non-unary operators such as ^, so
const pickName = ^name;
I wonder if this could be accomplished with a proxy object instead of new syntax.
const o = new Proxy(/* some implementation */);
const pickName = o.name;
pickName({ name: "Bob" }); // "Bob"
// maybe this could work too with a recursive proxy
// with handlers for access and invocation
const safePickBaz = o.foo.bar.baz;
safePickBaz({ foo: 20 }) // undefined
Does not destructuring assignment provide a means to achieve the requirement?
const getEmail = ({contacts:{email:_}}) => _;
const getEmailsList = users.map(getEmail);
const {contacts:{email:getEmail}} = user;
On Sat, Jun 22, 2019 at 10:59 AM guest271314 <guest271314 at gmail.com> wrote:
Does not destructuring assignment provide a means to achieve the requirement?
If the requirement is merely to write a function to pick properties, yes. If the requirement is to do that in a more concise, readable, reliable way, no.
If the requirement is merely to write a function to pick properties, yes. If the requirement is to do that in a more concise, readable, reliable way, no.
The term "readable" is entirely subjective. As far as am aware there is no standard for "readable" (in any language, coding or not). Whether an individual or program can read characters or symbols or not is based on the competency (if the reader is capable, by way of specific knowledge of the meanings of the characters or symbols contained in or on the document or artifact); pre-disposed biases, if any; and interpretation of the reader (based on their specific knowledge of the intent of the author). Even if such criteria for "readable" did exist in some institutional document, no author of code (or anything else) is bound to recognize or adhere to any such subjective and arbitrary criteria.
What specific definition of "reliable" is being used, and what are the cases that demonstrates using destructing assignment is not "reliable"?
Using a recursive Proxy to achieve this is a really smart @Barret.
Having said that, a recursive proxy implementation would surely not be possible without taking a significant performance hit. Thus, I don’t think Proxies are ideal for anything that is meant to be widely used throughout the codebase.
Also, something else that I think we should keep in mind since type systems like TypeScript have been widely adopted is how such type systems would be able to infer the type from a recursive Proxy.
The world is awash in subjectivity.
We can nevertheless hope to find broad agreement on at least a transitive ranking of attributes such as readability; if we don't think we can, then we are epistemological nihilists with no criteria whatsoever on which to base our language design decisions and this mailing list would have no raison d'etre, since we would never be able to align on anything.
However subjective the notion of readability, I think few would disagree that the first fragment below is more readable than the second.
.name
and
({name}) => name
The first is also more reliable by most measures, because it removes the
possibility of misspelling one of the instances of name
in the
second, which we would prefer not to rely entirely on type checkers or
linters to pick up.
Yes, to read the first does require additional knowledge, namely of the
fact that the syntax <dot>property
denotes a function to retrieve the
value of the property by that name. But this is no more a readability
problem than the fact that one must have knowledge of the English words in
a sentence in order for them to be "readable". Such knowledge is often
referred to by terms such as "cognitive footprint". Yes, this proposal does
have a cognitive footprint. But all language features have cognitive
footprints, requiring that people writing and reading code using the
feature have knowledge of the feature. The issue then becomes the size of
the cognitive footprint in relation to the benefit--an equation both sides
of which involve subjectivity...
Of course, I did not mean to imply that readability or reliability in and ot themselves are either necessary or sufficient for a new languge feature, There are many other aspects, as many as a dozen, which have been discussed and defined in earlier threads.
Bob
When we're dealing with code this small, I don't think readability is as
important of an element. Personally I would do ((a) => a.name)
, which is
short and, most importantly, very explicit about what it is doing. If you know what a function is and you know what a property is, you know what this code does. Adding additional syntax to a language requires increasingly esoteric knowledge of said language.
then we are epistemological nihilists with no criteria whatsoever on which to base our language design decisions and this mailing list would have no raison d'etre, since we would never be able to align on anything.
That can be the case. Agreement is not required by the parties for a specification or any other document to be drafted, published, and even enforced. The populace can absolutely disagree with the authors of the document. One or more parties can sign but ignore or extend beyond some or all sections of one or all agreements.
Re-read the proposal. Is the gist of the
proposal to substitute |>
, and or .
at const getEmail = .contacts.email;
as the first character after =
for =>
, meaning the initial .
following =
is interpreted as a function call,
equivalent to =>
? Can .name
be dynamic?
Can you include comments next to the examples at the OP detailing what each character is intended to mean in JavaScript, compared to the current specification of JavaScript?
E-40 uses the preferred pronouns he/him/his. There's no need to muddy the (40) Waters here.
—— Sandy
U+1F44D
In any event, re-read the proposal. Am certainly not opposed to the JavaScript language being capable of golf by default. Is the gist of the proposal to substitute
|>
, and or.
atconst getEmail = .contacts.email;
as the first character after=
for=>
, meaning the initial.
following=
is interpreted as a function call, equivalent to=>
? Can you include comments next to the examples at the OP detailing what each character is intended to mean in JavaScript, compared to the current specification of JavaScript?
This proposal has nothing to do with |>
. It is a variation of dot
notation, the classic notation o.p
that has been a feature of JS
since its inception, to treat .p
as a function (not a function call)
taking one argument and returning the value of the property p
in that
object. To put it a different way, if the object normally preceding the dot
is omitted, the construct is treated as a property picking function. It is
not a matter of the dot necessarily having to follow an equal sign, or
having some special meaning only that context; .p
not preceded by an
object is a function regardless of the context. To my knowledge, there is
no ambiguity in this notation. In other words, there is no case in which a
dot not following an expression and followed by an identifier is anything
other than a syntax error at present--please correct me if I'm wrong.
Although not mentioned in the brief propsoal, there is no logical reason
that the analogous property access syntax .[prop]
could not be
allowed. There also does not seem to any reason to prohibit the use of this
construct for arrays, so .[0]
could be the "head" function people
have been talking about for years.
Bob
I am guessing this doesn't allow any operations other than the "dot path" to a function or property... Are you comfortable with that? If so, why? I have found myself doing things like a=>a.x/2 . I couldn't do that in
proposed way, could I? Have you found, in your experience, that a "dot path only" return value is common enough to save you a lot of effort, and justify not being easily extendable to accept other operations, other than having to switch to the arrow syntax again, which could be cumbersome?
If you are comfortable with all these things, then I have no problem with the proposal really. I wouldn't lose anything. For me it would be like the "if" clause not requiring curly braces if there's only 1 statement - I simply always use curly braces - and might simply always use arrow functions - for the purposes of extensibility - but I'm not sure.
Thoughts? Have I missed something?
Let me correct one thing.
This proposal has nothing to do with
|>
.
What I meant to say is that the two proposals are not interdependent or
related, but since .p
is to be a function retrieving the value of
property p
, it can be used like any other function in a pipline, and
iso n fact plays quite nicely with pipelines.
const bedroomSize = house
|> getRooms
|> .bedroom // pick bedroom property from rooms object
|> calcRoomSize;
Bob
Howdy. First post to es-discuss.
I've been thinking about the proposal. I would recommend against it, main reason being that it makes the language a bit harder to read and understand at-a-glance.
Here's why. As an example, you've listed
const getEmail = .contacts.email;
as a possible use case. The problem with this is that what you're essentially doing is adding a third way to write a function (other than "const foo = x => x" or "function foo (x) { return x }"
Now, I don't mind the arrow operator since it automatically binds "this" and makes tracking the scope of "this" easier (as well as making "this" behave more like an object-oriented programmer coming from a primarily OOP language would expect "this" to behave). Trick is, of course that in so doing, we've added a "special occasion" where if we do need the function to have it's own "this" scope, we need to use the longer syntax. That "=>"
is shorter to type encourages it's use as the default, and when a coder looks at someone writing out "function" it warns them that something funky is about to happen with "this."
The problem with the proposal, as I see it, is that it creates a function that looks, at first glance, to be a variable assignment. Granted, that leading "." does look different from most variable assignments, but it's easy to overlook. Whether it's with an arrow function or the function keyword, when a function is defined, it is always defined with "()" somewhere in it. It is, in fact, what makes functions look different at a skim-level of reading comprehension, from things like assignments and operations.
By adding this new way of writing functions without () in the syntax, you increase the cognitive overhead of the programmer, which is something we want to avoid.
A concise programming language is not a programming language with the fewest characters, but the programming language with the fewest characters necessary to make meaning clear. I just don't think that the proposed syntax clearly indicates what it does, and violates the principle of least surprise.
So - that's my two cents as a person who isn't a language expert perse but does have to use ES on a daily basis.
It's still a good problem to solve, though, as (x) => x.some.property does
come up quite often. But perhaps this should be a proposal in a helper library like lodash that isn't something that all javascript programmers learning the language need to internalise. That way you could write:
const getEmail = _.drill("contacts.email", value_if_undefined) or const getEmail = _.drill(['contacts', 'email'], value_if_undefined)
get nearly the same amount of code golf, and be able to use it when you need it.
Every language feature adds cognitive overhead. It is not something that can or should be avoided. It should be minimized and balanced against other factors.
Whether some codebase uses the new .prop
syntax, or R.pick
(from Ramda), or pluck("p")
from RxJS, or some third-party or
homegrown utility, the programmer will have to learn it. For such a common
use case, it's better to have one thing for everyone to learn. Even then,
as with most other features, people could choose not to use it, or a
company could disallow its use in their styleguide if they really felt
strongly enough about it.
The problem with the proposal, as I see it, is that it creates a function that looks, at first glance, to be a variable assignment.
I don't understand this objection. How does .p
, which is the notation
we are talking about, look like a variable assignment?
As mentioned earlier in the thread, if there is concern that the leading
dot is easy to overlook--which I don't think is the case, and is less of a
problem in any case in most editors using monospaced fonts--there are
myriad alternatives, including any non-unary operator such as ^
, some
unique combination of symbols, a keyword such as pick
, or ?.
where
the ?
can be read as a placeholder for an object to be passed in
later. The proposal by no means rides on the specific symbol or notation
chosen. The advantage of the dot is that it is the long-established
notation for property access. We are merely extending that notion by
assigning a different (but related) meaning when the expression on the left is omitted.
I was expecting that someone brings up the brackets property accessor at some point. I would argue that there is a bit of syntactic inconsistency since usually when using the bracket accessors it is not preceded by a dot.
const getEmail = user => user["contacts"].email; // No dot between user & ["contacts"].
const getEmail = .["contacts"].email;
Having said that, the currently proposed Optional Chaining operator (Stage 2) does exactly that and more:
obj?.prop // optional static property access
obj?.[expr] // optional dynamic property access
func?.(...args) // optional function or method call
So I'd say that there is consistency with what is currently being proposed.
Regarding the Optional Chaining operator, which precedes the dot. How would that work? It would have to be something like this, if allowed.
const getEmail = user => user?.contacts.email;
const getEmail = ?.contacts.email;
It does look odd at first, but it’s quite simple is you think about it. We are just omitting the initial part of the expression.
More Examples with Optional Chaining operator:
// With optional dynamic property access.
const getUserEmail = user => user?.["contacts"].email;
const getUserEmail = ?.["contacts"].email;
// With optional function or method call.
const getJohnsEmail = getUserContacts => getUserContacts?.("John").email;
const getJohnsEmail = ?.("john").email;
The beauty of what is being proposed is that there is nothing new to learn or any new weird operator introduced. Any weirdness one might find with the expressions above will already have been introduced by the Optional Chaining operator. The only thing this does is to allow you to omit the initial (redundant) part of the expression.
Every language feature adds cognitive overhead. It is not something that
can or should be avoided. It should be minimized and balanced against other factors.
True, though I'd still argue that adding a new way to generate a function without either instantiating a function (with "()") or calling a function (with "()")
So - I get what you're saying.
As for how ".p" looks like a variable assignment, I mean specifically that it doesn't look like a function assignment (which it is) and looks more like a value assignment (which it isn't.) Granted, it doesn't 100% look like either. And yes, while companies can choose to not allow it in their own style guides, making it part of the language means that a user may encounter it, especially if they're trying to figure out how imported code works (not to mention, not every programmer in a company follows - or even reads - the styleguide.)
If I had to have this functionality in the language (and by no means have I ever had any problem with "const foo = x => x.prop;") it would be better
to define a new keyword that more explicitly explains the purpose.
(window || global).propDriller = function(arrayOfProperties, defaultReturn)
{
const driller = function(parameter, arrayOfProperties, defaultReturn) {
let working = parameter;
if (arrayOfProperties.length === 0) {
return working;
}
if (working === undefined || !(working instanceof Object)) {
return defaultReturn;
}
return driller(working[arrayOfProperties[0],
arrayOfProperties.slice(1), defaultReturn)
}
}
return function(parameter) {
return driller(parameter, arrayOfProperties, defaultReturn)
}
}
const getEmail = propDriller(['user', 0, "email'], defaultReturn)
I'd have no objection to this whastsoever (and the above could be used as a polyfill). But again, this is something that I think is a bit of a niche use case.
Minor point, but the vast majority of JS is written in corporate environments where code can't even be checked in unless it lints against the company's standard lint rules. Modern linters support an incredible variety of rules, including custom rulesets.
I am not saying that the availability of linters (or IDEs) should drive language design decisions, or that we should assume linters or IDEs are always used or build in dependencies on them. My point is merely that they do previde a way for companies to "opt out" of features that they don't like for some reason, and thus to some extent weaken the argument that some new feature is undesirable because every single JS programmer in the world will have to learn it.
I suppose what I'm making is a subjective argument, because there's no way to precisely measure "cognitive load" or "utility," just certain rules of thumb and guidelines passed down over the generations.
I suppose what it boils down to, is that I (subjectively) think that there's a very high price being paid for a (subjectively) low use case, when the existing syntax can be used without many more characters typed to solve the problem the new syntax is trying to solve.
The more I read this proposal, the more I feel the ideal solution is a preceding 'wildcard' character, to stand-in for a generic argument. If it wasn't in (widespread!) use, I'd suggest an underscore: ```const f = _.prop
Since it is, though, we need another one. How about a double-colon, seeing
as it can represent property access on other languages? ```const f = ::prop
```, ```const g = ::[compProp] ```, ```const h = ::?optProp ```
The problem is the same unless you have a way of "gluing" an expression as
a "shorthand-function" e.g. :.prop1 / :.prop2
won't be interpreted as a
single function that performs x.prop1 / x.prop2, but rather an attempt to
perform division with 2 functions
I'ld say, if there is no valid reason why a wildcard is required for the feature to actually work we should not add any. Else we would be just be depriving future features from using that symbol. Also, it does start to look a bit crowded with symbols if you consider the optional chaining operator.
Example:
const getUserEmail = *?.contacts.email
I think you are misinterpreting the intent of the proposal. It is not intended to handle logical expressions, that's way I called it Selector Expression :-)
Generalize this far enough, and you wind up with something not far from this: tc39/proposal-partial-application
Isiah Meadows contact at isiahmeadows.com, www.isiahmeadows.com
Also, without a leading token, a selector expr with the optional chaining operator inside a ternary operator would be ambiguous.
const contactSelector = true ? .contacts.email : .contacts.phone;
From: Isiah Meadows Sent: 27 June 2019 19:18 To: Michael Luder-Rosefield Cc: Simon Farrugia; es-discuss Subject: Re: Re: Proposal: Selector/Select Expression
Generalize this far enough, and you wind up with something not far from this: tc39/proposal-partial-application
Isiah Meadows contact at isiahmeadows.com, www.isiahmeadows.com
Not exactly, since the optional chaining operator is ?.
with no space in
between.
The space character/no space character would probably only be a limiting factor for golf. The differennces should be clearly explained (at each proposal, eventual specification) for disambiguation nonetheless.
How can the Selector/Select Expression be used with
Array.prototype.find()
? What happens when the property is not defined?
For example using the same code for more than one browser
const stream = [canvasStream, videoTrack].find(({requestFrame: _}) => _);
the property requestFrame
is either defined or not defined at
canvasStream
or videoTrack
depending on the implementation.
Although the assigned variable can be reduced to 1 character at
destructuring assignment, there is still the redundancy of writing _
again on the right side of =>
.
If the property is not found, is the result undefined
?
What is the least amount characters necessary using Selector/Select
Expression with find()
?
const stream = [canvasStream, videoTrack].find(.requestFrame);
?
How is the oppsosite written
const stream = [canvasStream, videoTrack].find(!.requestFrame);
?
If the intent is to find the first entry with a truthy value for the
requestFrame
property, then the proposal is array.find(.requestFrame)
.
If the "wildcard" syntax is used, then it would be
array.find(?.requestFrame)
.
On Thu, Jun 27, 2019 at 5:30 PM guest271314 <guest271314 at gmail.com> wrote:
How can the Selector/Select Expression be used with
Array.prototype.find()
? What happens when the property is not defined?For example using the same code for more than one browser
const stream = [canvasStream, videoTrack].find(({requestFrame: _}) => _);
the property
requestFrame
is either defined or not defined atcanvasStream
orvideoTrack
depending on the implementation. Although the assigned variable can be reduced to 1 character at destructuring assignment, there is still the redundancy of writing_
again on the right side of=>
.If the property is not found, is the result
undefined
?
Since .prop
is defined to be identically semantically to o => o.prop
,
yes, the function .prop
applied to an object with no property named
prop
returns undefined
.
then the proposal is
array.find(.requestFrame)
.Since
.prop
is defined to be identically semantically too => o.prop
, yes, the function.prop
applied to an object with no property namedprop
returnsundefined
.
Has the opposite, !
and !!
preceding .prop
, const d = [a, b].find(!.c);
or const d = [a, b].find(!(.c));
been
considered?
And async
functions const d = [a, b].find(async(await(.c)));
?
Agreed in that it's not ambiguous - you have to disambiguate it with a
space for the same reason you have to use a+ +b
instead of a++b
in
minified code to avoid ambiguity when specifying a + +b
. So a?.b:.c
would be invalid, but a? .b:.c
is not.
On Thu, Jun 27, 2019 at 16:48 Bob Myers <rtm at gol.com> wrote:
Not exactly, since the optional chaining operator is
?.
with no space in between.On Thu, Jun 27, 2019 at 1:37 PM Simon Farrugia <simonfarrugia26 at gmail.com> wrote:
Also, without a leading token, a selector expr with the optional chaining operator inside a ternary operator would be ambiguous.
const contactSelector = true ? .contacts.email : .contacts.phone;
--
Isiah Meadows contact at isiahmeadows.com, www.isiahmeadows.com
If missing, the expectation is that it's return undefined
just like how
a.foo
returns undefined
if a
has no property "foo"
. It's just
shorthand for x => x.foo
and similar.
Note: the wildcard syntax ?.foo
would itself not require this. It'd
require a space after the ?
in ternaries if the Elvis operator proposal
a ?? b
comes along (and a grammatical edit isn't made to clarify ??.
gets parsed as ? ?.
), but it would not otherwise be ambiguous.
Selector/Select Expression
Doing functional & reactive programming is currently really verbose in JavaScript.
Hopefully this issue will be alleviated with the addition of the pipe operator in the near future.
One things you end up doing most when doing fp is doing simple selections (mappings) on objects & arrays. This unfortunately becomes really verbose and repetitive.
What I'm proposing is to be able to collapse/simplify selector arrow function expressions like this:
to something like this:
More examples:
I think this would work really well, particularly in conjunction with the pipeline operator, resulting in more concise and expressive code improving readability.
This is just syntactic sugar, but same as in the case of the pipeline operator, selector functions are so intrinsic and commonplace to any code base, that I would think it's worth considering.
I would appreciate hearing your thoughts. Thanks.