Skip to content

Instantly share code, notes, and snippets.

@mh-mobile
Last active May 4, 2020 13:15
Show Gist options
  • Save mh-mobile/e240d06ba176642a57ecbad04096f4c8 to your computer and use it in GitHub Desktop.
Save mh-mobile/e240d06ba176642a57ecbad04096f4c8 to your computer and use it in GitHub Desktop.
JavaScript Iterate
#!/usr/bin/env node
Array.apply(null, { length: 10 }).forEach((_, i) => {
console.log(i);
});
#!/usr/bin/env node
let times = (n) => {
return (f) => {
Array(n)
.fill()
.map((_, i) => f(i));
};
};
let log = (i) => {
console.log(i);
};
times(10)(log);
#!/usr/bin/env node
Array(10)
.fill()
.map((_, i) => {
console.log(i);
});
#!/usr/bin/env node
Array.from(Array(10), (_, i) => console.log(i));
#!/usr/bin/env node
Array.from(Array(10)).map((_, i) => {
console.log(i);
});
#!/usr/bin/env node
for (let i of Array(10).keys()) {
console.log(i);
}
#!/usr/bin/env node
let i = 0
do {
console.log(i)
i++
} while (i < 10)
#!/usr/bin/env node
for (let i of [0, 1, 2, 3, 4, 5, 6, 7, 9]) {
console.log(i);
}
#!/usr/bin/env node
function* times(x) {
for (let x = 0; x < 10; x++) {
yield x;
}
}
for (let i of times(10)) {
console.log(i);
}
#!/usr/bin/env node
for (let i = 0; i < 10; i++) {
console.log(i);
}
#!/usr/bin/env node
const jsdom = require('jsdom');
const { JSDOM } = jsdom;
const dom = new JSDOM(``);
const { document } = dom.window;
const jquery = require('jquery');
const $ = jquery(dom.window);
$.each(Array(10), i => {
console.log(i)
})
#!/usr/bin/env node
let _ = require("lodash")
_.times(10, i => {
console.log(i)
});
#!/usr/bin/env node
const times = (x) => (f) => {
if (x > 0) {
f();
times(x - 1)(f);
}
};
let i = 0;
times(10)(() => {
console.log(i);
i++;
});
#!/usr/bin/env node
const times = (n) => (f) => {
let iter = (i) => {
if (i === n) return;
f(i);
iter(i + 1);
};
return iter(0);
};
times(10)((i) => {
console.log(i);
});
#!/usr/bin/env node
Number.prototype.times = function (f) {
return Array(this.valueOf())
.fill()
.map((_, i) => f(i));
};
(10).times((i) => console.log(i));
{
"name": "js-iterate",
"version": "1.0.0",
"bin": {
"array-apply": "./array-apply.js",
"lodash": "./lodash.js",
"underscore": "./underscore.js",
"spread-operator-foreach": "./spread-operator-foreach.js"
},
"dependencies": {
"jsdom": "^16.2.2",
"jquery": "^3.5.0",
"lodash": "^4.17.15",
"underscore": "^1.10.2"
}
}
#!/usr/bin/env node
[...Array(10)].forEach((_, i) => {
console.log(i);
});
#!/usr/bin/env node
[...Array(10)].map((_, i) => {
console.log(i);
});
#!/usr/bin/env node
let _ = require("underscore")
_.times(10, i => {
console.log(i)
})
#!/usr/bin/env node
let i = 0
while (i < 10) {
console.log(i)
i++
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment