dtao / lazy.js

Like Underscore, but lazier
http://danieltao.com/lazy.js/
MIT License
6.01k stars 268 forks source link

Cannot pick() numbers #207

Closed Redsandro closed 6 years ago

Redsandro commented 7 years ago
var map = {11: 12431, 22: 13242344, 33: 421412, 44: 12341, 55: 234524522}
var locs = [11,33,55]

Lazy(map).pick(locs).value()
// {}

Lazy(map).pick([11]).value()
// {}

Lazy(map).pick(['11']).value()
// {11: 12431}

// Workaround:
Lazy(map).pick(locs.map(key => String(key))).value()
// {11: 12431, 33: 421412, 55: 234524522}
dtao commented 6 years ago

I'm not sure this should work as described. It would only mask the fact that keys in objects really aren't numbers.

var map = {11: 12431, 22: 13242344, 33: 421412, 44: 12341, 55: 234524522};
Object.keys(map);
// [ '11', '22', '33', '44', '55' ]

I think it's reasonable to say that pick() only works with values that are actually keys of the given object. That said, I can update the documentation to make it clear that properties should be an array of strings.

Redsandro commented 6 years ago

@dtao you are correct. This is my mistake.

Altough if you can only pick strings, would it be an idea to String(keyToPick) in lazy.js? If keyToPick is already a string, nothing changes.

a = "test"
b = String(a)
a === b

One can argue that the developer using lazy.js would need to use proper types, but if there is no drawback in doing so, it would add syntactic sugar. And to me, while the first use case of lazy.js is speed, the second use case is wonderfully readable code.

E.g. every occurance of something like

Lazy(map).pick(locs.map(key => String(key))).pick(queuedIds.map(key => String(key))).value()

Could be written as:

Lazy(map).pick(locs).pick(queuedIds).value()

It would also save 2 iterations (map) from happening.