Can't use sugar.js functions

713 Views Asked by At

I tried to use sugar. Previously I used it one year ago and it worked good in such way:

> npm install sugar
[email protected] D:\work\test\test
`-- [email protected]
> node
>> require('sugar');
{ [Function: Sugar]
.....
 Array:
   { [Function: SugarChainable]
   .....
   compact: [Function: compact],
....
>> [1,null,2,undefined,3].compact()

TypeError: [1,null,2,undefined,3].compact is not a function
    at repl:1:24
    at ContextifyScript.Script.runInThisContext (vm.js:23:33)
    at REPLServer.defaultEval (repl.js:339:29)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.onLine (repl.js:536:10)
    at emitOne (events.js:101:20)
    at REPLServer.emit (events.js:191:7)
    at REPLServer.Interface._onLine (readline.js:241:10)
    at REPLServer.Interface._line (readline.js:590:8)

Any ideas what is wrong now?

2

There are 2 best solutions below

0
Soviut On BEST ANSWER

According to the SugarJS front page:

As of v2.0, native extension has become opt-in while supporting two new ways of interacting with the library. Sugar still believes in the safe extension of natives, however there are times when this is not appropriate, and this choice is now put in the hands of the user.

So you either need to use the chainable Sugar API:

var arr = new Sugar.Array([1,null,2,undefined,3]);
arr.compact();

This can be made into a one-liner like so:

(new Sugar.Array([1,null,2,undefined,3])).compact()

Or extend natives:

Sugar.extend();

While extending may seem simpler, there's a reason they've built it so you need to opt-in to this feature. Simply put, extending prototypes is dangerous as multiple libraries may want to extend the same prototypes and will cause collisions in their methods.

0
Mark On

To use these functions on native objects you need to call:

Sugar.extend();

More here: https://sugarjs.com/quickstart/