Git Product home page Git Product logo

sugar's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sugar's Issues

Feature: String method: wrap aliases pad, 3 paramaters

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>

UPDATE

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

Consider aliases for Python (and Ruby?) developers

Sugar is intended as a library that is directed toward Javascript developers. A couple things are implied by this statement:

  1. When native Javascript methods exist to do a job, I am not aliasing them with different names. Consistency with naming that can be considered "Javascripty" is part of an API that can be understood by newbies and veterans alike.
  2. Methods with completely new functionality will be given the most intuitive names possible. If this overlaps with other languages where similar functionality exists (as in the case of ActiveSupport's DateTime calculations), then so be it, but preference to intuitive naming will take a much higher precedence to maintaining common names with other languages. This is one area where Sugar is noticeably different from Prototype.

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!

overriding indexOf

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 'compatibility' mode

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

Use ES5 non-enumerable properties

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.

Fix: String methods: dasherize / camelize / underscore

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.

Array.indexOf function

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

Feature Request: Add a zip method to Array

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}]

Web Based Builder for Sugar

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.

Contribution Guide

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.

Array.each example on sugarjs.com/api missing a param

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…

Allow localization of Date functions

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 :-)

compact works differently than _.compact

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.

Fix: Non mutating method names pattern

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")

Sugar + Mongoose breaks strings

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") }
###

Compatibility with SpiderMonkey/CouchDb

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

Feature request: Array.trim()

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.

Feature: String methods: reciprocals

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?

Can't get D3 to work when Sugar.js is loaded under Firefox.

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.

JS resulting from Google Closure Compiler throws error

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.

Clashes with ES5

There are numerous clashes with ES5

  • Object.create as mentioned in a different issue
  • Object.IsArray vs ES5 Array.isArray
  • Object.keys doesn't have the same API

Personally I think it's foul play to get in the way of ES5

Add Utills for checks

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

Fix: replace titleize with captialize(true)

Instead of titleize, have capitalize accept a true or false parameter (defaulting to false):

  • easier API, one less method to remember, one method more intuitive
  • awkward grammer "titleize" gone ("eize" is unusual == undesirable)
  • awkward semantic gone ("titleize is not useful to communicate every-word-capitalized, there are zillions of ways to format titles, ask any typographer)

Alt solution:

Rename titleize to capitalizeAll.

angular compatibility

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)

Defect: Object.merge does not merge deep object structures

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' } }

Object traverse method

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

string.assign with empty string doesn't work as expected

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.

using SugarJS with SharePoint 2010 exception

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.

Sugar on NPM?

Are there any plans to put Sugar on NPM, it seems like a good fit for node development.

Array.add

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?

mongoose and sugar no likey

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.

Feature: Modularize features

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.

Bug in date format

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)

Suggestion - Time entry

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 :)

Feature Request: partial object matches for array.find()

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'}

Specify the size of the Minified JS File

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.