andrewplummer / sugar Goto Github PK
View Code? Open in Web Editor NEWA Javascript library for working with native objects.
Home Page: https://sugarjs.com/
License: MIT License
A Javascript library for working with native objects.
Home Page: https://sugarjs.com/
License: MIT License
Sugar date functions are really great, but they only work in english.
I used Datejs previously for this kind of work on dates, it had a pluggable language system.
It would be great to have the same system for Sugar.
I'm willing to contribute the French localization once it's ready :-)
dasherize
, camelize
, underscore
should somehow be enhanced to deal with, optionally, spaces, \s
in regex terms.
I am not sure of what the code would be, but some sort of boolean flag probably. The thing is camelize already takes one parameter so...
because this is an issue common to all 3 dasherize, camelize, and underscore perhaps the best solution is to make a common first-param among all of them, a boolean to specify if \s
should also be replaced. Then params unique to each one can follow.
There are all sorts of use cases for this in a web context, when dealing with url slugs, css class names, and mixing/matching with JS functions in various patterns.
recive this {2424} {Oct201110} {11111111} | {1204Mon Oct 24 2011 16:50:42 GMT+0200 (Jerusalem Standard Time)}:{1010}:{4242} ({305010Not Yet Supported297201110Not Yet Supported})
when the format is this:Date.create().format('{dd} {Mon} {yyyy} | {12hr}:{mm}:{ss} ({timezone})');
also i did this i recive this:
the func i use print this (part of class)
_updateClock: function ( )
{
var currentTime = new Date ( );
var currentHours = currentTime.getHours ( );
var currentMinutes = currentTime.getMinutes ( );
var currentSeconds = currentTime.getSeconds ( );
// Pad the minutes and seconds with leading zeros, if required
currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;
// Choose either "AM" or "PM" as appropriate
var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";
// Convert the hours component to 12-hour format if needed
currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;
// Convert an hours component of "0" to "12"
currentHours = ( currentHours == 0 ) ? 12 : currentHours;
// Compose the string for display
var currentTimeString = Date.create().format('d Mon year | 12hr:m:seconds (tz)');
// Update the time display
$(".Header_CurrentTimeDate").text('');
$(".Header_CurrentTimeDate").text(Date.create().format('d Mon year | 12hr:minutes:s (timezone)'));
}
this is output:
24 Oct201110 11Not Yet SupportedpmMon Oct 24 2011 16:59:49 GMT+0200 (Jerusalem Standard Time) | 1204Mon Oct 24 2011 16:59:49 GMT+0200 (Jerusalem Standard Time):10591055430Not Yet Supported49:49 (305910Not Yet Supported297201110Not Yet Supported)
Currently I believe you have to match on an entire object, but it'd be excellent if you could match against just parts.
var objs = [{ id: 1, title: 'Object 1'}, { id: 2, title: 'Object 2'}]
objs.find({id: 1}) // should return { id: 1, title: 'Object 1'}
Hey,
I was wondering, if that Array.add would take multiple new values:
var a = [];
a.add('my', 'sweet', 'values');
and for adding values at a specific index, use Array.insertAt();
That would make more sense to me. What you guys think?
when using SugarJS with SharePoint 2010, a JavaScript exception is thrown in one of SharePoint script files..
but if I remove Sugar the exception is gone
exception: Sys.InvalidOperationException: 'cancel' is a reserved name that can't be used as an enum value name.
It would be fruitful for Sugar's users (and its Authors) to create some comparisons to other similar libraries. I'm starting a list of libs that Sugar could compare use-cases with:
https://github.com/arshaw/xdate
I have just used the Date demo on the Sugar website and it looks great for dates and datetimes, but lacks a little when only entering a time.
Thus I come to you with a suggestion.
Make it possible to tell Sugar: "What I parse now is only (or most likely) times, no dates involved."
And then be able to parse as many weird time entries as possible.
Wether it should be done via a new interface or a parseTime on Date, I have no idea.
It is purely a self-centered suggestion. I have a need of it, but I have no idea if anyone else might find this usefull. And I have not been able to find anything else that does a descent job of this.
In any case, Sugar looks great :)
Instead of titleize
, have capitalize
accept a true
or false
parameter (defaulting to false
):
Alt solution:
Rename titleize
to capitalizeAll
.
what i mean
u handle string and numbers array and object
what about diffrent type of check lets say check if what u recive is a bool or convert at to a type,
check diffrent types of vaild fields and more
I want to set deep parameters in an object. I thought fromQueryString
does what I want, but I can not set an object to which the parameters are added, but I found you are using a method called setParamsObject
which does what I want. A counter part like getParamsObject
would be then needed too.
Here a jQuery example which better explains what I want: http://benalman.com/projects/jquery-getobject-plugin/
Seeing this problem when both D3 and Sugar.js are loaded (most recent versions) on Firefox 5 and 6. Everything works as expected on Safari/Chrome.
D3 is here: http://mbostock.github.com/d3/
Consider the following example, which selects an element, creates and appends a child element, and then attempts to set its attributes:
var svg = d3.select("#chart").append("svg:svg").attr("width", 500).attr("height", 300);
FIrefox will fail, complaining that this.setAttribute
is not a function.
Calling calling append
creates and returns a new selection group, calling attr
on iterates on each item and attempts to call setAttribute
on that item. It's similar in concept to jQuery, expect that D3 selection groups are nested arrays, so in this case [ [ svg:svg ] ]
.
From what I could determine, the attr
method is called in the context of [[ svg:svg ]]
, while it's supposed to be called on the svg
element directly.
Sugar is intended as a library that is directed toward Javascript developers. A couple things are implied by this statement:
I do acknowledge, however, that certain methods names can be counterintuitive for programmers coming from other languages (specifically Python and Ruby keep coming up), despite having more intuitive naming if you coming at it from a fresh start. I think that aliasing some methods can give us some common ground here.
Clearly I can't do that for all methods for all languages, but I think there are some "quick win" methods I can alias, specifically for Python-based methods (where there is a lot of functionality overlap) that can make Sugar more intuitive for those people. I don't speak Python or know the exact functionality of the methods in question, so I'm relying on people to help me out by adding methods they think should be aliased here. I will keep it updated... So far I've seen 2 that might make nice aliases:
Array#contains (for ES5 standard Array#some)
Function#partial (for Function#fill)
Please add to these!
There are numerous clashes with ES5
Personally I think it's foul play to get in the way of ES5
This method could be used to trim all elements in an array (leaving an element untouched if it is not a string). Obviously, trimLeft and trimRight can be added as well.
Are there any plans to put Sugar on NPM, it seems like a good fit for node development.
Another new date library. Worth checking out in contrast to sugar. Anything to learn/improve on for sugar here?
A simple generator that creates a numerical array: http://docs.python.org/library/functions.html#range
Array.range(3); // [0, 1, 2]
Array.range(1, 11); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Array.range(0, 30, 5); // [0, 5, 10, 15, 20, 25]
...
I don't think that can be lazy evaluated in JS?
Consistently provide reciprocal functions so that code can read better. It is often easy to stick a !
or not
(in CS) before methods to get at what we want, but a often nicer solution is to let the method communicate for us.
Maybe this doesn't always make sense because it adds a lot to the api, and not in consistent ways (i.e. the negation grammar might be doesnt
, not
, or unique like remove
... and further the name might change i.e. from has
to have
).
Currently has Reciprocal
add remove
isBlank notBlank (or isNotBlank ?)
has doesntHave
endsWith doesntEndWith
startsWith doesntStartWith
This is slanted to native english speakers, being easy for us to predict reciprical names, but I question the wider use. But does it really matter? People can always choose which style they want, the method name or the syntax structure !
/not
What do you think?
I'd like to suggest perhaps enabling a 'compatibility' mode for sugar so I at least have an option to use sugar methods if sugar doesn't play well with a particular library/codebase
eg
var Sugar = require('sugar')({compatibility: true}) // I know this is wrong, but something like this would be good
…so that I can still have access to sugar's methods, without extending ANY native prototypes.
Sugar.object.isArray()
Sugar.date.milliseconds()
Those date methods are particularly headache-saving, and I'm crapped off I seem to have no option to use them.
Or perhaps you could do something where you can turn sugar on/off at will:
sugar(function() {
// get freaky with sugar
})
// everything back to normal
Extending native prototypes is a neccessary evil.
But to make things easier on people attempt to use Object.defineProperty
and set the enumerable
flag to false.
Example:
var fn = function() {
console.log(arguments);
}.after(3);
...
fn(1);
fn(2);
fn(3); // Something like [1, 2, 3] instead of only the arguments of the last call of fn.
Sugar's Object.create appears to clash with the native Object.create. The method signature and behaviour seem quite different, check the docs at MDC. Perhaps rename Sugar's Object.create?
Today I toyed with enderjs for a few hours.
It seems sugar fails via the ender compile
method.
Here are the steps to recreate it:
ender build sugar
ender compile
Uncaught TypeError: Object 65 has no method 'ka'
Other ender js libs don't do this, such as bean
. From what I can tell, something goes wrong when sugar
and gcc
meet? It would be nice to have this fixed but I myself wouldn't know where to start.
From the homepage "Sugar will never overwrite methods that already exist" -- in what context is this meant? i.e. you obviously override Array.indexOf.
Sugar is a Jack of all Trades kind of script; however some of the potential developers may be interested on only a small part of the Library, for instance not everyone is going to find the hiragana/katanaka table useful.
This is a key feature considering how nice the script is.
If you have an Array of functions, and you try to locate one using indexOf, the function is treated as a filter, causing unexpected behavior.
var f1 = function(){}
var f2 = function(){}
var arr = [f1, f2]
assert(arr.indexOf(f2) == 1) // fails
Look here https://raw.github.com/gist/661000/c10aa59ddcd5f354a11522251ae75c26f93204d6/debounce-prototype.js
debounce with possibility to run the function immediately, useful if you use debouce for button clicks, executing the function ASAP, ignoring double click, usage:
$('button').click(function(){
console.log('clicked');
}.debounce(1000, true));
You don't have to wait 1000msec for function to execute.
Thank you for Sugar, bye.
Would be a nice shortcut for array.indexOf(element) > -1
.
http://stackoverflow.com/questions/1181575/javascript-determine-whether-an-array-contains-a-value
This may very well be a deliberate design decision but I thought I'd mention a trouble I ran up against.
I have a map function that returns an array that may have some both some class references (actually fn references per the way javascript defines classes) and some blank values (nulls). Underscore.js has a compact
method that does return my class references. Sugar's compact
method did not.
var fn = function(){};
var arr = [null, fn, null, null];
_.compact(arr) // => [fn]; //underscore.js
arr.compact() // => []; //sugar.js
This stems from how the isNaN
function evaluates the fn
reference. I'm not sure if this is a browser specific issue (using Firefox) or an issue with the ECMA5 spec. If this is the actual intended way it's supposed to work, it seems odd to me.
Title says it all :)
Cheers.
i noticed that arrays have destructive and non-destructive methods. I am guessing there is more of this throughout the lib. My issue here is that it confuses in the API in my mind. You have methods that do the same thing, different only in their destructive nature. What I would like is that a pattern is created so that the destructive and non-destructive methods have predictable forms and almost duplicate the namespace.
ruby solved this beautifully with the !
symbol being part of the method name. In JS we cannot do that of couse, but something should be done because trying to remember include
is a non-destructive form of add
for arrays (etc) is a real pain. It also hurts the API by bloating the namespace needlessly.
Here are some questionable pattern ideas to get the ball rolling...
ND D
add add$
add_
ADD
x.add (namespace it in a sub-object, like a 'x' for "danger!". In coco (a CS dialect) you could do this: [1,2,3].!.add)
o.add
x.add
Xadd (or without the object namespace)
xadd
I'm kind of liking the idea of x
namespacing destructive variants; easier to understand and read. I'll never have to second guess my code and think "wait, is that the right version of the method".
my_big_array.X.add("test")
my_big_array.x.add("test")
my_big_array.add$("test")
my_big_array.xadd("test")
How about a change or watch event that fires on object changes, like described here:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/watch
http://stackoverflow.com/questions/1759987/detect-variable-change-in-javascript
That would really complete sugar.js.
sugar.js gives a lot more functionality than backbone.js models. Only the change binding is missing.
Correct me, if this idea is way off. Its 6am in the morning and I have to go to bed :)
Sugar is already registered for NPM which is great for front-end package management.
But for front-end sugar.js still has no package management.
I think it would be prudent to consider registering for ender.js:
love the lib, love it! but I am experience clobbering issues with another great app, mongoosejs ... will see if I can identify more issues about why there is a conflict but wanted to throw it on your radar.
First of all really great work! I think this will my standard library for all my javascript projects :)
Curring is nice but something the parameters are badly placed. Can you add the partial function from http://ejohn.org/blog/partial-functions-in-javascript/ ?
Me again ;) I need a Python like zip method. There is a jQuery implementation: http://plugins.jquery.com/project/zip
I would call it zip cause it is the same principle as your zippers ;)
Implementation detail: When you call it on the array the array represents you keys and the given array are your values. E.g.:
var arr1 = [1,2,3];
var arr2 = [4,5,6];
var zipped = arr1.zip(arr2); // {1:4, 2:5, 3:6}
Maybe it should also possible to zip multible arrays to one e.g.
var arr1 = [1,2,3];
var arr2 = [4,5,6];
var arr3 = [7,8,9];
var zipped = arr1.zip(arr2, arr3);
Which can result in:
{1:[4,7], 2:[5, 6], 3: [5,9]}
or the classic result which also python does:
[[1,4,7], [2,5,6], [3,5,9]]
Discussion on stackoverflow: http://stackoverflow.com/questions/4856717/javascript-equivalent-of-pythons-zip-funciton
Python doc: http://docs.python.org/library/functions.html#zip
Or a new idea to access the results in a easier way would be to define a resulting object:
var arr1 = [1,2,3];
var arr2 = [4,5,6];
var arr3 = [7,8,9];
Array.zip({arr1 : arr1, arr2 : arr2, arr3 : arr3}) // [{arr1 : 1, arr2 : 4, arr3 : 7}, {arr1 : 2, arr2 : 5, arr3 : 8}, {arr1 : 3, arr2 : 6, arr3 : 9}]
Minor bug in docs on site for Array.each:
Example says:
[1,2,3,4].each(function(n) {
// Called 4 times: 3, 4, 1, 2
}, true);
When it should probably say:
[1,2,3,4].each(function(n) {
// Called 4 times: 3, 4, 1, 2
}, 2, true);
Note missing index
param.
}, 2, true);
If the site was on github :D I'd have changed it myself, but alas…
Sometimes you would like to access prop.prop.prop.prop-or-method (etc.) of an object dynamically, through some parameter or options object in a function, that is declared as a string. I think Sugar could facilitate this nicely by adding a traverse method which accepts a string, splits on '.', digs down to the last part, and returns that part.
attic =
dust:
bad_for_health: true
quantity: 56000
value: 0
antiques:
... etc
some_method = (a)->
Object.traverse attic, a
some_method("dust.quantity")
> 56000
Let the potential Developers interested in Sugar know the file size without having them to download the library. This is important especially for Web Developers.
I don't know if it is a bug or a feature when it is a feature it should be documented. Following example:
Object.merge({ foo : { bar : 'World' }, foo : 'bar'}, { foo : { foobar : 'Hello' }});
Expected result:
{ foo : { bar : 'World', foobar : 'Hello'}}
Actual result:
{ foo : { foobar : 'Hello' } }
If it's possible could Sugar be broken into modules similar to the approach of other libraries like MooTools?
I found your Date features better suited for my app than those found in Date.js. As such, I swapped Sugar.js in for Date.js. I am undecided just how much of Sugar I will use since my app already relies heavily on Underscore.js. I honestly prefer the native extensions of Sugar, but I'm just not ready (yet) to do a large refactoring. Still, your Date features have no overlap with any Underscore.js features. It would be nice if I could just include Sugar.date.js rather than the entirety of Sugar. Likewise, there are several language features involving Thai and such that I will likely never use so it would be nice to omit those.
A simple string method to wrap text. Useful for quotes, tags (not ideal way of course, but handy in a pinch), and other hard-to-itch use-cases. Mozilla has a non-standard dumbed down version called quote
: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/quote
Here is how I am thinking of the method (in coffeescript)
# with one param
"help".wrap "*"
> *help*
# with two params
"help".wrap "<h1>", "</h1>"
> <h1>help</h1>
pad
already achieves the above (minus the first argument). So in lieu of that, here's an updated idea:
wrap
aliases pad
because it is the more intuitive / meaningful name in that case
pad
takes a third optional paramater, for the text to pad right (defaulting to whatever is padding left)
# contrived var setup, you imagine something more dynamic than this
name = "Joe"
greeting = "Hello"
question = ", how are you doing today?"
name.pad 1, greeting, question
name.wrap 1, greeting, question
> Hello Joe, how are you doing today?
name.wrap 2, greeting
> Hello Hello Joe Hello Hello
name.padLeft 1, greeting
name.wrap 1, greeting, false
> Hello Joe
I'm using sugar.js v1.1.1 and I'm trying to do the following:
"here is an empty string:{empty}".assign({ empty: "" });
I expect to get:
"here is an empty string:"
But instead, I get:
"here is an empty string:{empty}"
I also tried assigning my empty parameter to undefined, as well as using the numbered substitutors (e.g. {1}). Same result.
Are my expectations wrong here? Is this by design? Or is this a bug?
Any help on the matter would be appreciated. Thanks.
I suggest you put on the Readme a contribution guideline for those who're interested on using Sugar and contributing back to the open source project.
Also it would be nice to have a roadmap going about what's going on and what needs to be done, so we can give you a hand.
Strings are getting converted to objects when saving to MongoDB via mongoose. Here is a test case:
###
npm install mongoose sugar
must have a working mongo instance on localhost
###
mongoose = require 'mongoose'
sugar = require 'sugar'
Schema = mongoose.Schema
User = new Schema
name : String
name2 : { type: String }
User = mongoose.model 'User', User
mongoose.connect 'mongodb://localhost/sugartest'
# clear collection
User.remove {}, (err) ->
throw err if err
john = new User
name: 'John'
name2: 'Smith'
john.save (err) ->
throw err if err
User.findOne (err, user) ->
throw err if err
console.log user.toObject()
###
console output:
{ name: { '': undefined },
name2: { '': undefined },
_id: 4e5c0d0da68d7a0000000001 }
from mongo shell - db.users.find():
{ "name" : { "John" : null }, "name2" : { "Smith" : null }, "_id" : ObjectId("4e5c0d0da68d7a0000000001") }
###
doesn't work with angular.js
From firefox:
this.delay is undefined
[Break On This Error] a!="y")b+="y";return this.setFlags(b)}...){return clearTimeout(this.timer)}}); sugar-....min.js (line 89)
Impressive library! Would love to see an additional parameter to .format that provides the equivalent functionality of toFixed(). An example use case: representing 25 as "25.00".
I was trying to require the module with couchdb which uses spidermonkey but unfortunately it seems to break, I am not sure if it is indeed possible to do that, could you please let me know?
I get the following error when trying to require the lib/sugar.js
file:
<<"compilation_error">>, <<"Module require('lib/sugar') raised error (new TypeError(\"/()??/.exec is not a function\", \"\", 5759))">>
Thanks
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.