-
-
Save dshaw/1098209 to your computer and use it in GitHub Desktop.
Array goodies from twitter rap with David Herman, see wrap up here: http://twitter.com/#!/littlecalculist/status/89855977838485504
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://twitter.com/#!/littlecalculist/status/89848378682392576 | |
// http://twitter.com/#!/littlecalculist/status/89855977838485504 | |
// Unary Array.from() | |
Array.from = function( arrayish ) { | |
return [].slice.call( arrayish ); | |
}; | |
var divs = document.querySelectorAll("div"); | |
console.log( | |
Array.from( divs ) | |
); | |
// see console | |
Array.from( divs ).forEach(function( node ) { | |
console.log( node ); | |
}); | |
var filtered = Array.from( divs ).filter(function( node ) { | |
return !!node.classList.length; | |
}); | |
console.log( "filtered", filtered ); | |
// filtered [<div class="some classes" data-info="12"></div>] | |
var reduced = Array.from( divs ).reduce(function( prev, current ) { | |
return ( +prev.dataset.info ) + ( +current.dataset.info ); | |
}); | |
console.log( "reduced", reduced ); | |
// reduced 22 | |
console.log( | |
Array.from( divs[0].classList ) | |
); | |
var a = Array; | |
console.log( | |
// Now shorter then [].foo.call :) | |
a.from( divs ) | |
); | |
// Variable Arity Array.of() | |
Array.of = function() { | |
return [].slice.call( arguments ); | |
}; | |
console.log( | |
Array.of( "things", "that", "aren't", "currently", "an", "array" ) | |
); | |
// ["things", "that", "aren't", "currently", "an", "array"] | |
console.log( | |
Array.of.apply( null, [ "foo", "bar", "baz" ] ) | |
); | |
// [ "foo", "bar", "baz" ] | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="some classes" data-info="12"></div> | |
<div data-info="10"></div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment