8 ms·
Is this: Object.keys(envars) .map(envar => `${envar}=${envars[envar]}`) .join(' ') |> `$ ${%}` |> chalk.dim(%, 'node', args.join(' '))
by arp242 4y ago
Is this:
Object.keys(envars)
.map(envar => `${envar}=${envars[envar]}`)
.join(' ')
|> `$ ${%}`
|> chalk.dim(%, 'node', args.join(' '))
|> console.log(%);
Really better than:
console.log(chalk.dim(
`$ ${Object.keys(envars)
.map(envar => `${envar}=${envars[envar]}`)
.join(' ')
}`,
'node',
args.join(' ')
));
That's the real-world example they have (I reformatted the second one slightly, because it looks better to me). Neither seems very good to me, and the |> version doesn't really seem "less bad".
Can also write it as:
process.stdout.write(chalk.dim(
`$ ${Object.keys(envars)
.map(e => `${envar}=${e[envar]}`)
.join(' ')
}`,
))
console.log(chalk.dim('node', args.join(' ')))
Which seems clearer than either because it splits out "print env variables" and "print out node args". And it would be even better with some sort of helper to convert an object to k=v string:
console.log(chalk.dim(`$ ${dumpObj(envars)}`, 'node', args.join(' ')))
---
I also feel this:
> In the State of JS 2020 survey, the fourth top answer to “What do you feel is currently missing from JavaScript?” was a pipe operator.
Is the wrong way to go about language design. Everyone wants something different, and if you just implement the "top 5 most requested features" you're going to end up with some frankenbeast of a language.
- pharmakom 4y agoThe Hack proposal is horrible imo because it doesn’t look like JS anymore. The F# proposal is 99% of the benefit whilst being actually approachable.
- galaxyLogic 4y agoI think we should have BOTH. Use |> for the Hack proposal and -> for F# -style.
- hajile 4y agoI'd far rather save that for an alternative switch expression with pattern matching. const slowSum = (lst: {x: number}[]) => switch(list) { [{x}, ...y] -> x + slowSum(y) //not tail recursive [{x}, {x: y}] -> x + y //alias second x to y [{x}] -> x //handle length 1 [] -> 0 //handle length 0 }
- tracker1 4y agoHaving been watching, and a couple times playing with Rust... would definitely like a similar pattern matching system in JS. I still feel the C# syntax for this feels a bit alien `varname switch {...}`.
- pharmakom 4y agoAs an F# developer who also does some JS and Java this would confuse the hell out of me! |> is the best operator
- grumpyprole 4y agoThere's no need. The % placeholder can be used for a consise lambda syntax and would work with a F# application operator.
- masklinn 4y ago> The Hack proposal is horrible imo because it doesn’t look like JS anymore. I mean it looks exactly like JS with an additional % placeholder.
- mkl 4y agoAnd a lot more like JS than the F# proposal.
- pharmakom 4y agoHow so? JS already has operators, but placeholders is a totally new concept
- mkl 4y agoIs there another JavaScript feature that looks like a list of function names but which causes actions to be performed? Or operators that operate on both functions and values? The placeholders are very similar to variables, so do what they look like they do, and it's only the implicit definition that is new. The explicit placeholders feel much more like JavaScript to me than the implicit function calling of the F# proposal.
- pharmakom 4y ago- functions and lambdas are already first-class values in JS - we already have operators on values, such as + - |> is just another operator on values
- epolanski 4y agoIt absolutely is, but time and time again TC39 has followed few champions over the waves of people favoring F# pipes. It's incredible to me TC39 would rather have this monstruosity over F# pipes which are actually pretty similar to how most pipes work and read in most functional languages including unix `|` one.
- WorldMaker 4y agoOn the flipside, I think that this is still such an ongoing debate is part of why the pipeline operator is still stuck in Stage 2 and having trouble getting into Stage 3, despite being listed as a "priority" multiple times on and before 2020. TC-39 isn't blindly following anyone here, they seem to be dragging their heels hoping that someone comes along with an even better compromise between the styles.
- xigoi 4y agoBefore ES6: “The arrow function proposal is horrible imo because it doesn’t look like JS anymore.”
- pharmakom 4y agoIt’s a balance. I actually support the addition of the F# proposal, minus the await parts.
- antipurist 4y ago"Why did it take so long?" and "Pointless bloat!" reactions were much more common: https://news.ycombinator.com/item?id=3780367 https://news.ycombinator.com/item?id=3780367 https://news.ycombinator.com/item?id=6418337 https://news.ycombinator.com/item?id=6418337
- deleted 4y ago[deleted]
- BigJono 4y agoTC39 proposals often have rubbish real world examples that should never see the light of day in a JS codebase. It makes me really question the judgement of the people that are working on this language, and it explains how some of the shittier proposals manage to slip in and why the good ones are misused all over the place in every real world codebase when this is the kind of guidance devs have on where to use fancy new features. In a few years everyone is going to collectively lose their fucking mind once again and decide that ternaries are now the devil and every React component should be chock full of do expressions. I can see that coming clear as day. That might finally be enough to get me to throw in the towel if the also incoming decorator hell doesn't do it.
- stoned 4y agoI am still hoping that decorators might not pan out :fingers-crossed:
- recursive 4y agoWait, what's wrong with decorators? They seem pretty nice in python.
- tracker1 4y agoI like decorators as a concept... but there have been a couple different implementations now... the TypeScript version is probably the most broadly used, but there were others before it via Babel (formerly 6to5). I was an early adopter of the original decorators proposal as well as the F#-style pipeline operators. The more time has moved on and other bits made it into JS proper, I'm far more inclined to stick to what's "in the box"... Have even considered just writing straight JS + ESM (modules). Of course, I also like JSX, though not sure of any proposals of how to get that "in the box" as e4x died on the vine and a lot of other efforts didn't gain much traction either.
- DarkNova6 4y ago> It makes me really question the judgement of the people that are working on this language Only now?
- 4y ago
- dmix 4y agoJust because pipe's aren't the ideal solution for that convoluted example they decided to list doesn't mean they aren't still extremely useful for a consistent set of problems. Like anything they can be abused to make code less readable. I also have a feeling this doc lists every sort of usecase, not because they are advertising it as "always the better version", but because it's a design doc that needs to factor in edge cases, such as using a pipe following chained function calls.
- arp242 4y agoI'm just using the example they posted in the README as an "before-after". I think that's a reasonable thing to do when evaluating "do I think this would be a good feature?" Blame the author(s) of that document if you don't think it's a good example.
- dmix 4y agoThat seems to be missing the point of the document then. Before/after in a design doc isn't "this is a better way to do it".
- arp242 4y agoWhat is the point then?
- dmix 4y agoI don't see design docs as a tutorial on how to be a better programmer using a new syntax, the goal is to flesh out a new concept built on some fundamental ideas. You cherry picked one example of a tangled/messy block of code that they used to communicate specific idea around "left to right" comprehension and flow of the data using the new syntax. For that specifically it did a fine job. But that doesn't mean that's the way you should be writing code in the first place, given it started with a mess and only used one piece of syntax to change it. I will admit it's a poor example to open with. But for a design doc about exploring and debating ideas it's fine.
- progx 4y agoFor me not. In the Pipe example you must read first that something is done with the object and that it will be output at the end. If i read a code and i want to now what it will do, i wanna first read that it will output something. If that is what i search for, i read the nested code. With the pipe style i waste more time, even if the code looks clearer. I not overused example could look like this: console.log( Object.keys(envars) .map(envar => `${envar}=${envars[envar]}`) .join(' ') |> `$ ${%}` |> chalk.dim(%, 'node', args.join(' ')) ) If i don't care about console.log, i don't have to read the nested code.
- NhanH 4y agoMethod chaining is better, but you need the library/class/ code to support it. If you got a bunch of function it can’t help you. Pipe operator is useful for when you use other people’s code. On the other hand, pipe is less useful when you don’t have partial application of function built-in. So yeah I think this is not worth it.
- travisgriggs 4y agoThis works when your language doesn’t have an implicit “return nothing” as it’s default. Nothing says “imperative” like “this routine may or may not take input, but you ain’t getting nothing back out of it.” Ironically, OO gets thrown under the bus a lot lately because it ain’t functional. But in reality, early OO languages like Smalltalk and CLOS were much more functional in this regard, you always had an implicit return of self, which could be chained easily. I (over)use the piping operator (|>) in Elixir a lot. I just like the way it reads. But one thing I don’t love, is that it’s not an easy sequence to type.
- OkayPhysicist 4y agoElixir's pipe mechanics probably aren't a great model for implementing pipe operators in existing languages. A large part of what makes |> work in Elixir is the steadfast commitment to f(most_likely_to_be_piped_param,other,params) argument ordering in the standard library.
- epolanski 4y agofluent apis are a matter of preference. I personally find pipe style much more readable.
- thdc 4y agoI do prefer the piped version mainly because it removes annoying nesting but that's not high on my prioritized list of discomforts. The issue of deeply nested function calls is a thing, but I just use some temp variables to avoid it when it really starts looking ugly. Then again, this is my typical opinion to a lot of the proposals - I see what this is useful for but I haven't experienced enough pain to really argue for it. However, if it does make it into the spec then I will use it probably because it's there. I also recognize my stance as one that not many people like in other contexts because it can be interpreted as me not looking to improve my situation. But on the flip side I think cluttering the language specification with a lot of superficial syntactic sugar is a mistake.
- Joker_vD 4y agoSome people, it seems, just love to write things in A-normal form but dislike naming temporary variables. Solution: pipe operator.
- Aldipower 4y agoBoth examples are not good. They are both very unreadable and an example of slapping things together without to look on readability.
- jakear 4y ago> Everyone wants something different, and if you just implement the "top 5 most requested features" you're going to end up with some frankenbeast of a language. Very much this. They need a new question on the survey "does JavaScript need new syntax or can we just leave it alone and work on perf/tooling/etc. of the existing stuff without throwing a bunch of new junk in"?
- kzrdude 4y agoYou have nested backticks there. Is this really real code?
- arp242 4y agoYes, you can do that in lambdas: > `${50}: ${[1,2,3].map(a => `${a+1}`)}` '50: 2,3,4' Whether that's a good idea or clear code is another issue. But it's allowed.
- tgv 4y agoSo their argument in favor of this fugly new operator is that some people write unreadable code? That's not the language's fault. As they say, you can write FORTRAN in any language. This just gives them a new tool to make things even worse. chalk.dim(Object.keys(envars) .map(envar => `${envar}=${envars[envar]}`) .join(' ') |> `$ ${%}`, 'node', args.join(' ')) |> console.log(%); And it doesn't even work on objects. Lame. I know the reason: JS has no typing. Still is lame.
- 8note 4y agoI'm trying to compare this to the jQuery kinda syntax X .this() .that() .then() .do() .a() .thing() And I expect this to let me keep that chain going for when I need to run a static function against the chain X .this() .that() .then() .do() .a() .thing() |>JSON.stringify(%)
- mkl 4y agoTo format code as code, indent two spaces: https://news.ycombinator.com/formatdoc https://news.ycombinator.com/formatdoc
- dns_snek 4y agoI won't speak about the specifics of the chosen syntax (Hack/F#) but in general - absolutely. With pipes you can visually follow the manipulations and function calls in the order that they happen instead of being forced to scan the code inside-out & outside-in, matching parentheses and function call parameters in your head, while still visualizing intermediate results to get 1 final return value. I find Elixir code much easier and quicker to understand, in large part thanks to its (admittedly, imperfect) pipe syntax. Code written in this way is also much easier to debug because you can quickly add `console.log`, breakpoints, or equivalent between the pipes. I find this unnecessarily time-consuming and difficult to parse and I'd likely raise some flags in a code review: console.log(chalk.dim( `$ ${Object.keys(envars) .map(envar => `${envar}=${envars[envar]}`) .join(' ') }`, 'node', args.join(' ') )); Without pipe syntax, I'd refactor this to: const envStr = Object.keys(envars) .map(envar => `${envar}=${envars[envar]}`) .join(' '); const styled = chalk.dim(`$ ${envStr}`, 'node', args.join(' ')); console.log(styled); But you often find yourself having to add additional logic, e.g. to scrub sensitive values, so it would probably end up closer to: const sensitiveEnv = [...]; const envStr = Object.keys(envars) .filter(envar => !sensitiveEnv.includes(envar)) .map(envar => `${envar}=${envars[envar]}`) .join(' '); const styled = chalk.dim(`$ ${envStr}`, 'node', args.join(' ')); console.log(styled);
- cokeandpepsi 4y agothe refactored version of the example is much worse
- rektide 4y agowhy? are you of a 'pointfree' opinion? what are your concerns? https://wiki.haskell.org/Pointfree https://wiki.haskell.org/Pointfree personally i detest pointfree syntax. having intermediate values makes it much easier to step through code with a debugger & see what is happening. and it gives the reader some name for what the thing is, which is incredibly useful context. the enablement of pointsfree styles is one of my main concerns about potential pipe operator syntaxes: the various syntaxes that have been raised often introduce implicit variables which are passed, and i greatly fear the loss of clarity pointsfree style brings. maybe there's something beyond the pointsfree vs not debate here that i'm missing, that makes you dislike the refactored example. personally i greatly enjoy the flatness, the step by step production of intermediate values, each of which can be clearly seen, and then assembled in a last final clear step. that is much more legible to me than one complex expression.
- DarkNova6 4y agoWait, design by committee is not a good thing? Gasp I can only hope this leads to Javascript becoming even more unbearable. Perhaps only this can weaken Google's resistance to WASM.
- scotty79 4y ago> Neither seems very good to me, and the |> version doesn't really seem "less bad". For me the piped version seems way better, way cleaner, with cleanly separated processing steps. I don't like nested steps because for nesting multiple arguments functions your expression tends to grow in both directions and parts belonging to the same step tend to end up really far from one another and clearly distingushes them from data that's pushed through the pipeline. % is short so it keeps parts of the same processing step together. This syntax also enables you to express which part is the data to be processed, what are the processing steps and what are additional parameters of the processing steps.
- hajile 4y agoThe F# syntax looks/acts a lot better here (especially paired with lodash). I also feel your code example wasn't done in the way people would actually use pipes. import {map, join} from 'lodash/fp' //iterators have better performance envars |> Object.entries |> map(([key, val]) => `${key}=${val}`) |> join(' ') |> x => chalk.dim('$ ' + x, 'node', join(' ', args)) |> console.log Even without lodash, it's still easy to read. envars |> Object.entries |> x => x.map(([key, val]) => `${key}=${val}`) |> x => x.join(' ') |> x => chalk.dim('$ ' + x, 'node', join(' ', args)) |> console.log For sake of completeness, here's the hack-based variant envars |> Object.entries(%) |> %.map(([key, val]) => `${key}=${val}`) |> %.join(' ') |> chalk.dim('$ ' + %, 'node', join(' ', args)) |> console.log(%)
- captainmuon 4y agoThe F# syntax would endlessly confuse me though. I'd always wonder whether |> join(' ') means join(x, ' ') or join(' ', x).
- hannasanarion 4y agoin F# syntax the right side is always a unary expression, so `|> join(' ')` means `|> join(' ')(x)` (the requirement being that join(' ') returns a function that takes one arg)
- hajile 4y agoThe top example relies on Lodash/fp having curried functions you can use. The middle example would be using native stuff which is why you have the wrapper function (kinda like you'd have a function wrapping a callback)
- de_keyboard 4y agoThe F# syntax is an incredibly simple bit of syntactic sugar. Just replace this: x |> f With this: f(x) For the join example, you must do this: xs |> (x => x.join(' ')) It de-sugars to: (x => x.join(' '))(xs) ... which of course is simply: xs.join(' ')
- mschuetz 4y agoAll of the examples look unreadable and hard to debug to me. Why not something like this rather than one massive nested instruction? let keys = Object.keys(envars); let text = keys.map(envar => `${envar}=${envars[envar]}`).join(" "); console.log(chalk.dim(`$ ${text}`), "node", args.join(' ')); That way you can easily inspect and verify the intermediate values at runtime. Helpful for you to see if your code works as expected, helpful for others to see what the code is doing.
- hinkley 4y agoBad examples can doom a project. It's amazing how much time people can spend on a solution while completely ignoring the documentation. Pipes are probably better used on a set of operations that takes input and runs multiple functions on the input, rather than fiddling with string concatenation multiple times. What do we use multi-pipes for in unix? I can't recall the last time I used one where the middle action wasn't a filter of some sort. grep -v to remove lines, or colrm or awk print to cherry-pick fields from a multi-field line. Once in a very long while I need to do three commands with filters between them. Beyond that it's too complicated and I make a script to handle several of the steps.
- lucideer 4y agoThe issue with taking examples from real-world code & converting them is that there's no guarantee the real-world code is good. It usually isn't, so you're comparing bad with bad. A more aggressive reformulation would be to prefix the original code with const envOutput = Object.keys(envars).map(envar => `${envar}=${envars[envar]}`).join(' '); const argsOutput = args.join(' '); Leaving the example being converted as simply: console.log(chalk.dim(`$ ${envOutput}`, 'node', argsOutput)); vs envOutput |> `$ ${%}` |> chalk.dim(%, 'node', argsOutput) |> console.log(%); This more clearly highlights the obvious limitations of pipelines - piping envOutput but not 'node' nor argsOutput is a jarring syntax-mix here. Though I think it offers some hope for them working well in other scenarios - possibly in curry-heavy applications.
- scotty79 4y agoIt's not jarring. It expresses what is the subject that's being processed and what are additional parameters of the processing steps. This allows to keep all parameters of each processing step together and processing steps easily visually separable.
- lucideer 4y ago> It's not jarring. It expresses what is the subject that's being processed and what are additional parameters of the processing steps. Only if the first parameter of the function is the sole subject & subsequent parameters are "additional". Which isn't the case in this example: all params are equal subjects.
- scotty79 4y agoRight. `chalk.dim()` is probably not the best thing to use as an example for this. But you can still think about this as merging in two additional pipes into the one you are processing. So 'node' and argsOutput are just very short pipes that you are merging into the flow of current one. Btw... chalk API feels super weird.
- johnny22 4y agoIs that how they really do it? I haven't actually seen that happen. There's no reason not to take popularity into account for some measure, as long it's not the ONLY thing you take into account.
- masswerk 4y ago> I also feel this: >> In the State of JS 2020 survey, the fourth top answer to “What do you feel is currently missing from JavaScript?” was a pipe operator. > Is the wrong way to go about language design. Let's call it Signor Rossi language design… "Signor Rossi cosa vuoi? … E poi, e poi, e poi" (Viva la felicità by Franco Godi [1]) [1] https://www.youtube.com/watch?v=UrKKMtjNWCI https://www.youtube.com/watch?v=UrKKMtjNWCI
- vorotato 4y agoThis and, they probably didn't mean the pipe operator from the niche language "hack".
- runarberg 4y agoDuring the 2020 survey there were two versions of this operator on the table smart mix and F#. A few months later the committee advanced a third option Hack, which is kind of like smart-mix but always requires the placeholder token. I suspect that many developers expressed their desire for this operator under the believe that it would make their style of programming easier, which F# indeed does for many code bases, particularly those that use libraries such as fp-ts or rxjs. However the advanced version fails to deliver that
- scotty79 4y agoI'll bite: let _= Object.keys(envars).map(envar => `${envar}=${envars[envar]}`).join(' ') _= `$ ${_}` _= chalk.dim(_, 'node', args.join(' ')) _= console.log(_); This is possible in current JS syntax. You can also cram it into one line with semicolon: let _= Object.keys(envars).map(envar => `${envar}=${envars[envar]}`).join(' ') ;_= `$ ${_}` ;_= chalk.dim(_, 'node', args.join(' ')) ;_= console.log(_); So it's basically Hack syntax for pipes with just ;_= instead of |> and _ instead of %. And you need to 'mark' the beginning of the pipeline with `let _=` Additional 'benefit' is that until you leave the scope you can access output of the last pipe through _. You can always use ;_= for consistency and pre-experess you intent to use the piping in the current scope by doing `let _;` ahead of time: let _; ;_= Object.keys(envars).map(envar => `${envar}=${envars[envar]}`).join(' ') ;_= `$ ${_}` ;_= chalk.dim(_, 'node', args.join(' ')) ;_= console.log(_); Full disclosure, I hate all of the above but I love Hack syntax with |> and %. To better confer the direction of the pipe you might even use the letter that is oriented to the right: let D; ;D= Object.keys(envars).map(envar => `${envar}=${envars[envar]}`).join(' ') ;D= `$ ${D}` ;D= chalk.dim(D, 'node', args.join(' ')) ;D= console.log(D); And if you want to use your pipe as an expression or return it from the function , instead of ; might be better: let D; return D= take(D) ,D= bake(D) ,D= serve(D); Surprisingly semicolon auto-insertion doesn't interfere with this: let D; return D= take(D) ,D= bake(D) ,D= serve(D);
- notpushkin 4y ago;D
- scotty79 4y ago;D is perfectly legal syntax too. Btw I think I'll name this operator duck ,D= Maybe the pipe syntax extension will be introduced if we threaten to make duck operator a thing?
- moogly 4y agoThis is the code equivalent of that "illegal LEGO techniques" thing to me.
- sirsinsalot 4y agoThey're all horrific
- jameshart 4y agoThe thing I dislike about it most is the constantly-rebound % variable. It means something different in each line. In this case they have elected to keep it as a string throughout the pipe, but this ‘more pipey’ version of the code has it start out as an array then turn into a string halfway through the pipe, which feels dangerous (and is presumably why they didn’t take the example this far): Object.keys(envars) |> %.map(envar => `${envar}=${envars[envar]}`) |> %.join(' ') |> `$ ${%}` |> chalk.dim(%, 'node', args.join(' ')) |> console.log(%);
- tracker1 4y agoNot really... F#-style pipeline syntax would be a bit more explicit about it, assuming you could use % for a variable name... Object.keys(envars) |> % => %.map(envar => `${envar}=${envars[envar]}`) |> % => %.join(' ') |> % => `$ ${%}` |> % => chalk.dim(%, 'node', args.join(' ')) |> % => console.log(%); To be honest, I've pretty much given up the hopes that TC39 would actually resolve pipelines and decorators at this point... I think it's been around a decade now.
- jameshart 4y agoBut then why would you call all those different variables ‘%’? Reading this version though I also notice something else that the F# style enables that the Hack style doesn’t which is that it supports destructuring. So in F# style, I can more easily make pipe steps that pass on multiple values in a structured object or array, then access them easily down-pipe.
- tracker1 4y agoUnfortunately F# pipelines have been rejected a few times by TC39 to advance... I used it for a while via Babel/6to5, but I gave up (like with decorators) after many years of no advancement. I doubt I'll see either any time soon.
- wheelerof4te 4y agoSELECT 'Jerk' FROM jerkings_tab; Is this Perl? DROP jerkings_tab; Is this really Perl?
- ryanmcbride 4y agoI feel like your first example was written kind of in bad faith but still, literally yes your first example is better than your second.
- ravenstine 4y agoThe flaw with that approach to language development is that there's no limiting factor. Can you imagine a survey where everyone says they're satisfied with the language as-is? Of course not. That's statistically impossible. Even if 99% of the needs of developers are satisfied by a language, people are going to eventually answer that they'd like something that the language doesn't have, and that's always the case. Let's say JavaScript implemented nearly every single language feature that's ever been invented. That is except the goto statement. Upon being surveyed on what they think is currently missing from JavaScript, a significant number of developers will have to respond with goto. Does that mean JavaScript is actually "missing" goto and that it was a mistake that it was never implemented in the first place? Of course not.
- rubyist5eva 4y agoAs somone that use to write a lot of functional-style code (in ruby), and generally prefers functional style, and have created many many many "pipelines" like that in ruby code - I've actually started to "regress" to "status-quo" (as the article puts it) mostly because I work with developers that don't understand functional style and it just becomes point of contention in review that I just don't care about getting into anymore. I can see this same kind of thing happening with this operator in JS-land (I may be wrong, haven't written any significant javascript in years, but people tend to be stubborn). I just write things as stupidly as possible now, and just do the second one even though there are nicer "ruby-ways" to do them - maybe this is "bad" but I find it easy to read and grok...and it doesn't cause arguments during review <.<
- stouset 4y ago> Is this… ${new-style} really better than… ${old-style}? Yes! A hundred thousand times yes! I have not seen this syntax in JavaScript before, but just by having the vague notion that it's pipe-like, I was able to generally understand what was happening within seconds of reading it. I'd have to read up on the syntax a bit to confidently write code in this style, or perhaps to fix a bug (does "${%}" do what I think it does) but I can quite literally comprehend the author's intent almost at almost the same speed as I can read. 1. get all the keys of envars. 2. convert every key into a "var=value" format. 3. put a space between them all 4. stick a dollar sign in front of the whole thing 5. no clue what the `chalk` library is for? a. this *appears* to prefix a "node ${args}" call with the previously-created environment variable bits b. that tracks with what we've seen so far c. close enough for now 6. log the whole thing Note that even without knowing what chalk is or does, the flow of everything makes it extremely clear what exactly the high-level outcome is supposed to be. We're building up a string like "$ FOO=bar BAZ=qux node --arg thing --arg2 more_args". We're doing something fancy with it that I don't quite know about just yet, but the above knowledge makes it very easy to fill in that gap. With the second one, I have to construct a tree in my head 1. console.log… a. the result of chalk.dim, which is i. all the env vars ii. mapped to key=value format iii. joined by a space b. ^ actually do chalk.dim on that thing above i. sorry, back up, there were some additional arguments c. ^ actually do chalk.dim on the above with 'node' and space-separated args i. I think this concatenates them? ii. double-check [1.a] to confirm iii. did I miss `args` defined somewhere in [1.a]? A. no, it's apparently inherited from scope 2. ^ actually log all the above a. wait is this a correct reading, based on reassembling the above? The confusion is compounded by not knowing the details of chalk. I have to jump backwards and reason about what the result of a non-linear chunk of steps is to make sure my guess is consistent. I have no opinion on the merits of this particular syntax, its implementation details, or in comparison to alternate proposals of similar ideas. I'm sure there's worthwhile debate to be had on those details. But from a high level, I'm a fan. My head is not a meat-based tree traverser and I'm guessing most people's isn't either. Human brains are big fans of linear narratives. While I love movies and shows like Memento and Westworld, this kind of disjoint storytelling is quite literally done for the purpose of generating confusion and not for promoting comprehension. Also, there may already exist better ways of expressing this particular example linearly and succinctly. If there is, I'd probably prefer that. Worst-case scenario you can always deconstruct nested function calls into sequential variable assignments, and maybe that's the "best" answer here instead of new syntax. But is an approach that can be understood linearly from start to finish clearer than one that requires mental tree-walking? Yes. Yes yes yes yes yes.
- quickthrower2 4y agoI don’t like complex nesting inside the string though. That might be a nitpick as you can split that out without the pipe operator.
- mkl 4y agoJavaScript has been a frankenbeast of a language right from its inception, by design. However, the 5th most requested feature in that poll is somehow "functions", and "sanity" also appears in the results, so this particular source may not be a good one.
- aabbcc1241 4y agoWithin the current js syntax, you can make the code looks readable with a chain or pipe with a simple function https://github.com/beenotung/tslib/blob/master/src/pipe.ts https://github.com/beenotung/tslib/blob/master/src/pipe.ts You can even use an array if you don't need to peek the value in the middle of a chain of operations Example: createChain( Object.entries(envars) .map(([key, value]) => `${key}=${value}`) .join(' ') ) .map(keys => `$ ${keys}`) .map(pattern => chalk.dim(%, 'node', args.join(' '))) .use(line => console.log(line)) In each step, you can name the intermediate result accordingly to it's meaning, should be more readable than calling it %