Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    jsweibo
    @jsweibo

    https://github.com/jashkenas/underscore/blob/36eef3c118041ae6386b6bba2b48b099e57ca0e5/underscore.js#L861L864

    Hello, everybody.
    when I was reading the source code of throttle, I can't understand the usage of line 861 to line 864.
    sorry, My English is not good, but I will try to describe my question clearly.
    My question is "if remaining <= 0 is true, why still need call clearTimeout() to cancel the timer ?"
    In my opnion, if remaining <= 0 is true, It means timeout must be null or undefined. So It don't need to call clearTimeout().
    If you can give me a hand, I'll be appriciated.

    jsweibo
    @jsweibo
    I got it. Because of setTimeout() can not guarantee execute on time.
    tesoy-xx
    @tesoy-xx
    <script type="text/javascript" src="underscore.js"></script>
    <script type="text/javascript" src="underscore.object.builders.js"></script>

    Can you share a screenshot of the actual usage?
    I might be able to do that. One sec.
    It's probably something funny with the data, but a screenshot of the usage might help rule out any silly errors.
    Yeah, I wanted to make sure I was expecting the right stuff to happen.
    Nope, that didn't work.
    So that's the code, being debugged. You can see "theseOrders" is an array of non-empty objects.
    Hmm, that url doesn't work for me
    Can you just drag it into Gitter?
    imgpsh_fullsize.png
    imgpsh_fullsize.png
    And there's the result of checking what "thisOrder" is. I expected it to be one of the non-empty objects. Is that a correct expectation?
    I think it might just be confusion about how the debugger is working
    I think you are not yet in the scope of the callback, you are still in the outer scope
    It always comes back to scope. What would you recommend?
    And thisOrder is not defined in the outer scope.
    Just add a few new lines inside your callback so that it's easier to set a breakpoint in there.
    Screenshot (1).png
    Ah. I see what you mean.
    It is populated now in the debugger, but not filtering as I expect it to.
    What is the value of thisOrder?
    Now that it's populated, it's the same as one of the entries in the theseOrders array.
    It could be because I am edgily trying to compare Date Strings.
    (is this one bigger than that one, etc.)
    Yeah, that's probably not safe
    What format is the date string?
    one of them is yyyy-mm-dd and the other is yyyy-mm-ddThh:MM:ss
    I would add console.log(a, b, a <= b)
    My very quick research into ASCII codes told me that would PROBABLY work.
    Yeah, it seems dangerous (you should probably try to find a better way), but i would expect it to work as well.
    Capture.PNG
    Apparently it doesn't work.
    I was expecting 0 to evaluate to less than 2.
    headdesk
    Capture.PNG
    That's better. It still doesn't filter out the last two objects from the resulting array, though.
    Well, that's all right. It's 5 here. I'm taking off. Thank you for your help!
    I think I've got it to a working state. I appreciate it!
    Great!
    Have a good weekend.
    I'm learning cordova right now and trying to use underscore's isEqual function. I understand it comes with cordovalib, does anybody know how i can use it in my index.js?
    i also don't usually do webdev
    Iā€™m not familiar with Cordovalib. Do you have code you can share?
    Fixed it: needed to npm install underscore, then copy underscore-min.js to platforms/[platform]/platform_www and do <script ... src="underscore-min.js"/> in my index.html
    @captbaritone I was fetching an object from a server and checking equality locally
    working on a custom version of cordova-plugin-fetch and was testing it in an app, so did this in my index.js:
    tryFetch: function() {
    var parentElement = document.getElementById("fetchjson");
    var fetchingElement = parentElement.querySelector('.fetching');
    var verifiedElement = parentElement.querySelector('.verified');
    var invalidElement = parentElement.querySelector('.invalid');

    fetchingElement.setAttribute('style', 'display:block;');
    verifiedElement.setAttribute('style', 'display:none;');
    invalidElement.setAttribute('style', 'display:none;');
    
    // mvpnFetch should work, cordovaFetch shouldn't
    //cordovaFetch('http://server.local/json.json')
    mvpnFetch('http://server.local/json.json')
        .then(function(response) {
            return response.json();
        })
        .then(function(json) {
            console.log(json);
            fetchingElement.setAttribute('style', 'display:none;');
            if (_.isEqual(json.body, expectedJsonFromFetch)) {
                verifiedElement.setAttribute('style', 'display:block');
            } else {
                invalidElement.setAttribute('style', 'display:block');
            }
        })

    }

    const expectedJsonFromFetch = {
    "hello": "world",
    "number": 1,
    "subobject": {
    "key": "val"
    },
    "array": [
    "one",
    2,
    true
    ]
    }

    ( )
    Milagros Vazquez
    @emevazquez
    hi people
    im new here
    i need some help with js
    bitflame
    @bitflame
    Hi everyone.
    Swapnil Javanjal
    @SwapnilJavanjal

    Hello Guys,
    I am getting " '_' is not defined no-undef" error. Below is my code.

    import React from 'react';
    import ReactDOM from 'react-dom';
    import './index.css';
    //import AuthorQuiz from './AuthorQuiz';
    import Sum from './AuthorQuiz';

    function ClickMyButtons({numberOfButtons, onSelection}) {
    const makeButton = v => <button key={v} id={v} onClick={event =>
    onSelection(event.target.id)}>{v}</button>;
    return <div>
    {_.range(1, numberOfButtons+ 1).map(makeButton)}
    </div>;
    }

    ReactDOM.render(<ClickMyButtons numberOfButtons={99} onSelection={console.log} />,
    document.getElementById('root'));

    serviceWorker.unregister();

    I did npm install underscore as well, but no luck.

    Julian Gonggrijp
    @jgonggrijp
    @SwapnilJavanjal Do you have a import _ from 'underscore'; anywhere? You need that.
    J.C. Wren
    @jcwren_twitter
    Good evening. I'm still wrapping my head around promises and such, and I'm hoping that someone can explain why the second async of the example below throws TypeError: Cannot read property 'range' of undefined, although the first async works.
    'use strict';
    
    const _ = require ('underscore');
    
    var v = _.range (1, 10);
    
    (async (_) => {
      await Promise.all (v.map (async n => {
        await console.log (n);
      }));
    }) ();
    
    (async (_) => {
      await Promise.all (_.range (1, 10).map (async n => {
        await console.log (n);
      }));
    }) ();
    Kevin Partington
    @platinumazure
    You've shadowed the _ variable in both of the outer async functions. In the second one, you then try to use _.range but _ no longer points to the Underscore object. This isn't really specific to async/await, as you could do the same thing with an ordinary IIFE.
    If you just don't use a parameter name in your outer arrow function, then _.range should point to the right function and work correctly
    @jcwren_twitter See above
    J.C. Wren
    @jcwren_twitter
    Oh, that was stupid. I totally didn't associate the underscore in the async parameter as being the underscorejs library name. There's no actual argument necessary for the outer async, so the underscore there is useless. I was using this code from an async/await tutorial as an example, and that's why I got bitten. I don't know what purpose the underscore serves here, since the tutorial doesn't use the underscorejs. library.
    const mapLoop = async _ => {
      console.log('Start')
    
      const promises = fruitsToGet.map(async fruit => {
        const numFruit = await getNumFruit(fruit)
        return numFruit
      })
    
      const numFruits = await Promise.all(promises)
      console.log(numFruits)
    
      console.log('End')
    }
    J.C. Wren
    @jcwren_twitter
    OK, I'm out of here. Thanks for you help on that, @platinumazure .
    Julian Gonggrijp
    @jgonggrijp
    @jcwren_twitter Potentially interesting for underscore-like algorithms that work async: async library
    Kevin Partington
    @platinumazure
    @jcwren_twitter Yeah, in that example it does nothing. I can safely say that declaring the parameter and then not using it at all (as is done in that mapLoop example) is... a bit silly. Glad you're in good shape now!
    The correct syntax for no parameter async arrow function is async () => {}
    iscelinetam
    @iscelinetam
    hello
    matteocacciola
    @matteocacciola
    hello, I am building my VueJs based app with webpack. It uses underscorejs too
    I am experiencing this error
    can someone help me, please?
    underscorejs version is 1.10.2
    2020-04-07-145446_1920x1080_scrot.png
    jgonggrijp @jgonggrijp reacted to the issue on github :point_up:
    Cameron Beccario
    @cambecc_twitter
    Hi @jgonggrijp. Thanks so much for the conversion to es module syntax! I've been looking forward to this for a long time, hoping that one day tree shaking could be used on underscore to reduce bundle sizes. I'm giving it a try now and noticed that webpack's ability to remove dead code is somewhat limited due to all the side effects. I have some ideas to make it more tree-shakable and would like to contribute, but I wanted to check first if you had noticed the same and had plans to improve it (or concluded it was impossible).
    Cameron Beccario
    @cambecc
    For example, converting all of the calls to restArguments into statically exported functions.
    Julian Gonggrijp
    @jgonggrijp
    @cambecc Hey glad you appreciate it!
    Yes I'm aware of the limitation in threeshaking. Rollup has the same problem. I think the best solution is to chop the entire library into tiny modules. I'm working on a plan to convince Jeremy that this is the right thing to do.
    Converting the restArguments calls to straight functions works too, but at the expense of increasing code size (or switching to ES6 syntax entirely, but that would require transpilation and probably increase code size even more). Also, it's only a partial solution because there are also lots of functions that really have to be generated from a function call.
    Julian Gonggrijp
    @jgonggrijp
    @cambecc I already have a completely modularized version of Underscore ready to push, so basically just waiting for agreement from Jeremy.
    Cameron Beccario
    @cambecc
    @jgonggrijp That's great to hear! Hopefully that can happen soon. Btw, I'm happy to test it out in the interim.
    Julian Gonggrijp
    @jgonggrijp
    @cambecc That's a very nice offer of you. I prefer to not have it out in the open yet, though. I'll make sure to keep you updated.
    Cameron Beccario
    @cambecc
    šŸ‘
    Danny Villa Kalonji
    @Danny-Villa
    Hi! I'd like to know supported browsers since I can't see it anywhere in the doc.
    Julian Gonggrijp
    @jgonggrijp
    @Danny-Villa it's IE8 and anything more standards-compliant.
    Julian Gonggrijp
    @jgonggrijp

    Dependency graph of the upcoming modular Underscore (jashkenas/underscore#2849): https://gist.github.com/jgonggrijp/61e9a00b8807cd41a2ffa73b8ad8cc7a/raw/dfc8879dadc1f0691c84a1f1063971067c344775/modular-underscore-dependencies.png

    Blue balloons are Object functions, Red is Utility, Orange is Function, Purple is Collection, Green is Array. Yellow arrows indicate direct and indirect dependencies on iteratee.

    Julian Gonggrijp
    @jgonggrijp
    The modularization branch was merged! Now I just need to write an article about how to get the most out of it, and then we'll be ready for the release. jashkenas/underscore#2849
    Grigoris Ntousakis
    @GNtousakis
    Hello!! Is anyone online? :))
    Julian Gonggrijp
    @jgonggrijp
    Hi @GNtousakis ! Yes, I am.
    Ario K
    @itsario_twitter
    hello
    anfengchen
    @anfengchen
    hello
    // Internal helper to create a simple lookup structure. // 'collectNonEnumProps' used to depend on '_.contains', but this led to // circular imports. 'emulatedSet' is a one-off solution that only works for // arrays of strings. function emulatedSet(keys) { var hash = {}; for (var l = keys.length, i = 0; i < l; ++i) hash[keys[i]] = true; return { contains: function(key) { return hash[key]; }, push: function(key) { hash[key] = true; return keys.push(key); } }; }
    anfengchen
    @anfengchen
    I think maybe there is something wrong in the native underscore.js function "emulatedSet" ? As hash inherit from Object.prototype, the 'contains' using hash[key] will cause
    problem. I hope someone can explain it. Thank you.
    Julian Gonggrijp
    @jgonggrijp
    @anfengchen I have not noticed any problems with this, but you might be right. Do you have example code that demonstrates a problem with it?
    anfengchen
    @anfengchen
    /********************************************************************************************
     * Native code in underscore.js
     * "emulatedSet" was called in "collectNonEnumProps", which aim to solve the ieEnumBug
     ********************************************************************************************/
    // Internal helper to create a simple lookup structure.
    // `collectNonEnumProps` used to depend on `_.contains`, but this led to
    // circular imports. `emulatedSet` is a one-off solution that only works for
    // arrays of strings.
    function emulatedSet(keys) {
        var hash = {};
        for (var l = keys.length, i = 0; i < l; ++i) hash[keys[i]] = true;
        return {
            contains: function(key) { return hash[key]; },
            push: function(key) {
                hash[key] = true;
                return keys.push(key);
            }
        };
    }
    
    var hasEnumBug = !{ toString: null }.propertyIsEnumerable('toString');
    var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
        'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'
    ];
    
    // Internal helper. Checks `keys` for the presence of keys in IE < 9 that won't
    // be iterated by `for key in ...` and thus missed. Extends `keys` in place if
    // needed.nonEnumerableProps
    function collectNonEnumProps(obj, keys) {
        keys = emulatedSet(keys);
        var nonEnumIdx = nonEnumerableProps.length;
        var constructor = obj.constructor;
        var proto = Object.prototype.toString.call(constructor) == '[Object Function]' &&
            constructor.prototype || Object.prototype;
    
        // Constructor is a special case.
        var prop = 'constructor';
        if (obj.hasOwnProperty(prop) && !keys.contains(prop)) keys.push(prop);
    
        while (nonEnumIdx--) {
            prop = nonEnumerableProps[nonEnumIdx];
            if (prop in obj && obj[prop] !== proto[prop] && !keys.contains(prop)) {
                keys.push(prop);
            }
        }
    }
    
    /*********************************************************************************
     * my test code
     *********************************************************************************/
    var obj = { toString: null, valueOf: 'value' };
    // in IE<9, the keys for obj will be []
    
    var keys = [];
    // keys will be [], but we expert ['toString','valueOf']
    collectNonEnumProps(obj, keys); // keys = []
    @jgonggrijp As I can't install IE8 in my computer, I don't know if my test is right simulation of IEEnumBug.
    Julian Gonggrijp
    @jgonggrijp
    @anfengchen I see what you mean. It could probably be fixed by changing the implementation of contains to return hash[key] === true;. I suspect nobody is trying to use Underscore with IE8 anymore, but please feel welcome to submit a PR and get the credits.