Sugar
Sugar copied to clipboard
Allow method prefix when extending
Proposal: Allow a prefix when extending methods to natives and their prototypes. This behavior was introduced by Agave.js. It would work like this:
Sugar.extend({
prefix: 'xx'
});
Once methods are extended they would be called with the prefix specified:
[1,2,2].xxUnique();
Adding this functionality would ensure further safety when using Sugar in extended mode.
next up, bikeshedding about how it should totally not be camelCase etc. JK, good one ;-).
(really, it might just as well be a function? To avoid any future bikeshedding. Not sure :D...)
Had the same thought myself :)
But, you mean a function as in a callback that passes the original name of the function?
Yes
Yep, that sounds reasonable. Make it versatile up front.
But camel-case by default :)
Oh, sure. In general, this (almost) allows two sugar versions side-by-side :)
One other possible variant of this (taken from here) is to have a single sugar
object that houses methods:
[1,2,3].sugar.max()
In effect, this would only be the difference between writing a .
or not from the users side, but would probably be more complicated to implement. I would say it's unclear if this would help avoid collisions or not. Just an idea for now.
Hey, thanks for your lib & efforts !
I would like to use the method prefix feature (or prefix object), this is most useful when extending object prototype.
I currently do something like:
Sugar.extend()
Sugar.Object.extend({
objectPrototype: true,
methods: ['keys', 'map', 'filter', 'find', 'reduce', 'values']
})
but this will most likely conflict with other tools.
Given the following options:
Sugar.Object.extend({
objectPrototype: true,
prefix: name => 'sugar_' + name,
})
var option1 = ({ a: 1, b: 2, c: 3 }).sugar_map((v, k) => v*2).sugar_values()
// OR
Sugar.Object.extend({
objectPrototype: true,
objectProxy: 'sugar',
})
var option2 = ({ a: 1, b: 2, c: 3 }).sugar.map((v, k) => v*2).sugar.values()
var option3 = ({ a: 1, b: 2, c: 3 }).sugar.map((v, k) => v*2).values()
I would prefer the 2nd or 3rd option if you find a more widely support method than Proxy (+ Polyfill)
For now, I'll use the following code (from your twitter link):
Sugar.extend()
const unwrap = {
get(target, name) {
if (name == 'raw') return target.raw
return new Proxy(target[name], {
apply(target, thisArg, argumentsList) {
return target.apply(thisArg, argumentsList).valueOf()
}
})
}
}
Object.defineProperty(Object.prototype, 'sugar', {
get() { return new Proxy(Sugar.Object(this.valueOf()), unwrap) }
})
Hi, yes I agree that prefixes when extending are a useful feature. Please +1 the top comment here to show your support for it! It is planned for the next minor version.
Proxies however are outside the scope of Sugar and are used for a different purpose here, so the implementation will not use them.