jashkenas / underscore

JavaScript's utility _ belt
https://underscorejs.org
MIT License
27.3k stars 5.53k forks source link

Make Underscorejs functions functioning on generators #2924

Closed ghost closed 3 years ago

ghost commented 3 years ago

note: I port my question on stackoverflow here.

I have dozens of functions acting on arrays. See here for the sake of illustration.

As you can see I am using Underscorejs for most operations.

However I want to write a transformation on my main iteratee which is a list of JSON objects like the following:

var listings = [{ title: 'title1', d: 0, desc: 'hello world', pass: 'qub7s1ya', tags: ["tag1", "tag2"] }]

As I want to really optimize performance, I want to write a transformer on desc values. I will be using lzutf8 for this; So that I store in disk and in memory only compressed values. On each Underscorejs operation I would like to act on the decompressed value of key desc.

Apparently, Underscore operations do not act on generators directly, so my question is how to achieve this ?

edit: I believe all operations of Underscorejs are sequential, so why not support generators ? or am I missing something ?

jgonggrijp commented 3 years ago

@bacloud14 Please include a link to the Stack Overflow question when you do this. I found it though:

https://stackoverflow.com/questions/67138146/make-underscorejs-functions-functioning-on-generators

I consider this a duplicate of #2147 and will close the current issue for this reason. I will still answer your question on Stack Overflow, because I believe the answer could be useful to a wider audience. Please clarify what exactly you're trying to do first, though, by updating your SO question as I've asked here.

ghost commented 3 years ago

@jgonggrijp thank you so much for the follow

ghost commented 3 years ago

for sake of illustration here is an example with getter attached at runtime which saved my day (instead of generators)

listings = [{ title: 'title1', d: 0, desc: 'oipfjezojifze', pass: 'qub7s1ya', tags: ["tag1", "tag2"] }]
listings.forEach(item => {
    Object.defineProperty(item, 'desc_', {
        get: function () { return (this.desc.toUpperCase()) }
    });
});
var results = _.where(listings, { desc_: "oipfjezojifze".toUpperCase() })
// it also returns the object intact
console.log(results[0].desc_)
// and other methods _#filter, _#findWhere, _#where, _#reject, _#pick do as well