The Underscored Importance of Underscore (JS)
阿新 • • 發佈:2018-12-28
As in the example above, Underscore functions are called like so:
_.functionName(arg1, [arg2, ...])
Here are a few functions that everyone wanted but didn’t have:
_.invert // returns a copy of the object where the keys and their corresponding values are switched.
_.invert({a: 'one', b: 'two', c: 'three'});=> {one: 'a', two: 'b', three: 'c'} // omg
Well slap my butt and call me Brenda. You mean you can look up the key of an object by its value? Unreal.
(The catch is that the values must be unique and able to be string-serializable but still wow)
_.functions // returns a sorted list of the names of every function property in an object.
_.functions({ // some object with methods });=> ["method1", "method2", "method3", ...]
Stop. The. Madness.
_.extend // shallowly mashes objects together, the first object being the dumpee
_.extend({a: 'one'}, {b: 'two'});=> {a: 'one', b: 'two'}
I am DONE.
Other than methods for objects, we also have methods like:
_.uniqueId // generates a globally unique ID. You can optionally pass in a prefix
_.uniqueId('swag');=> 'swag_14'
And last but not least… I will end this post with what I believe is a much-needed, appropriate point:
_.template // returns a function that can be evaluated for rendering. Useful for rendering bits from JSON data sources. TBT ERB LOL. The returned function can take a data object with keys corresponding to the variable in template.
let inspire = _.template("<p>The world ain’t all sunshine and rainbows. It’s a very mean and nasty place and I don’t care how tough you are it will beat you to your knees and keep you there permanently if you let it. You, me, or nobody is gonna hit as hard as <%= something %>. But it ain’t about how hard ya hit. It’s about how hard you can get hit and keep moving forward. How much you can take and keep moving forward. That’s how winning is done!</p>")
_.inspire({ something: "JAVASCRIPT" })
=> "<p>The world ain’t all sunshine and rainbows. It’s a very mean and nasty place and I don’t care how tough you are it will beat you to your knees and keep you there permanently if you let it. You, me, or nobody is gonna hit as hard as JAVASCRIPT. But it ain’t about how hard ya hit. It’s about how hard you can get hit and keep moving forward. How much you can take and keep moving forward. That’s how winning is done!</p>"