Elegant way to generate string from tagged template?

Ron Buckton rbuckton at chronicles.org
Tue Dec 23 17:14:20 PST 2014


For ES6 you could use http://github.com/rbuckton/QueryJS like this:

```
var a = [1,2,3];
var b = ["a", "b", "c"]
var c = Query
  .from(a)
  .zip(b, (a, b) => [a, b])
  .flatMap(a => a)
  .toArray()
  .join("");
```

Ron

Sent from my Windows Phone
________________________________
From: Brendan Eich<mailto:brendan at mozilla.org>
Sent: ‎12/‎23/‎2014 3:39 PM
To: es-discuss at mozilla.org<mailto:es-discuss at mozilla.org>
Subject: Re: Elegant way to generate string from tagged template?

Perhaps the most elegant way is functional composition on arrays, not
string hacking just-so imperative coding: zip composed with flatten and
join. You could even use underscore.js:

http://underscorejs.org/#flatten
http://underscorejs.org/#zip

but JS's OO standard library style prefers method chaining. Array lacks
standard zip and flatten, although concat does one level of flattening:

js> Array.prototype.flatten1 = function () { return [].concat.apply([],
this); };
(function () { return [].concat.apply([], this); })
js> Array.prototype.zip = function (b) { var r = []; var n =
Math.min(this.length, b.length) ; for (var i = 0; i < n; i++)
r.push([this[i], b[i]]); return r; }
(function (b) { var r = []; var n = Math.min(this.length, b.length) ;
for (var i = 0; i < n; i++) r.push([this[i], b[i]]); return r; })
js> ['a', 'b', 'c'].zip([1, 2, 3]).flatten1().join('');
"a1b2c3"

This is just a quick sketch. A real standard library zip would be a bit
more involved, ditto any flatten or flatten1 ;-).

/be
_______________________________________________
es-discuss mailing list
es-discuss at mozilla.org
https://mail.mozilla.org/listinfo/es-discuss
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20141224/695e6887/attachment.html>


More information about the es-discuss mailing list