Skip to content

Instantly share code, notes, and snippets.

@arturparkhisenko
Last active April 12, 2017 17:22
Show Gist options
  • Select an option

  • Save arturparkhisenko/bb0bc0a38a1fdb301de2 to your computer and use it in GitHub Desktop.

Select an option

Save arturparkhisenko/bb0bc0a38a1fdb301de2 to your computer and use it in GitHub Desktop.
iterate-through-object-properties-or-nodeList
// speed winners is: for-with-cached-length OR for-of-with-let > map > forEach
for (let key of iterable) {
// do stuff
}
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
// do stuff
}
}
// slowest, use usual for with Object.keys Array
Object.keys(obj).forEach(function(key) {
// do stuff
});
// through nodeList (ff<50, sf<11, old browsers fix)
var nodeList = document.querySelectorAll('div');
if (nodeList) {
for (var i = 0, nLl = nodeList.length; i < nLl; i++) {
// do stuff with nodeList[i]
}
// OR
// nodelist didnt have forEach
nodeList = [].slice.call(nodeList);
nodeList.forEach(function(element) {
// do stuff with element
});
// OR
// Convert to Array
const items = Array.from(nodeList);
// Use any array method
const filtered = items
.filter(item => item.textContent.includes('bat'))
.map(item => item.textContent = item.textContent + 'man')
}
// https://medium.com/devschacht/joel-thoms-functional-javascript-decoupling-methods-from-their-objects-9a2686096418
const map = f => x => Array.prototype.map.call(x, f);
// examples:
const items = document.querySelectorAll('div')
items.map(doSomething)
// => Uncaught TypeError: items.map is not a function
map(doSomething)(items)
// => [<div/>, ..., <div/>]
const value = 'Kitty Cat'
value.map(doSomething)
// => Uncaught TypeError: items.map is not a function
map(doSomething)(value)
// => ['K', 'i', 't', 't', 'y', ' ', 'C', 'a', 't']
const getFullName = ({ first, last }) => `${first} ${last}`
getFullName({ first: 'Max', last: 'Power' })
// => 'Max Power'
map(getFullName)([
{ first: 'Max', last: 'Power' },
{ first: 'Disco', last: 'Stu' },
{ first: 'Joe', last: 'Kickass' }
])
// => ['Max Power', 'Disco Stu', 'Joe Kickass']
const obj = {
0: 4,
1: 5,
2: 6,
length: 3
}
map(increase)(obj)
// => [5, 6, 7]
// composing 2 mappings
const mapDoSomethingThenStuff =
compose(mapDoStuff, mapDoSomething)
// carr
const increaseOne = x => x + 1
// partially applied map increase
const increaseMany = map(increaseOne)
increaseMany([1, 2, 3])
// => [2, 3, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment