ðŸŠī\zansh.in\js

JavaScript tinkerings.

forEach / break / continue / @@iterator

Loops of the standard and functional variety, breaking out of them, and skipping iterations.

💐  for / forEach()

function forLoop() {
let index = 0
let count = 0
for (; index < 1000; index += 1) {
count = count + 1
}
log('done, count === ', count)
}
function usingForEach() {
let count = 0
oneThousandItems().forEach(
(_, index) => {
count = count + 1
}
)
log('done, count === ', count)
}
const { log } = console
const oneThousandItems = () =>
Array.from({ length: 1000 })

ðŸŒļ  break / some() / every()

function breakLoop() {
let index = 0
let count = 0
for (; index < 1000; index += 1) {
if (index > 499) {
break
}
count = count + 1
}
log('done, count === ', count)
}
function usingSome() {
let count = 0
oneThousandItems().some((_, index) => {
if (index > 499) {
return true
}
count = count + 1
})
log('done, count === ', count)
}
function usingEvery() {
let count = 0
oneThousandItems().every((_, index) => {
count = count + 1
if (index < 499) {
return true
}
})
log('done, count === ', count)
}

🌚  continue / forEach()

function continuedLoop() {
let index = 0
let count = 0
for (; index < 1000; index += 1) {
if (index > 249) continue
count = count + 1
}
log('done, count === ', count)
}
function usingForEach() {
let count = 0
oneThousandItems().forEach(
(_, index) => {
if (index > 249) return
count = count + 1
}
)
log('done, count === ', count)
}

🌷  Object.keys() / values() / entries()

const stars = {
['🌟 Sirius A']: {
['🏛']: 'Alpha Canis Majoris'
},
['⭐ïļ Canopus']: {
['🏛']: 'Alpha Carinae'
},
['🔆 Rigil Kentaurus']: {
['🏛']: 'Alpha Centauri'
}
}
const keys = () =>
Object.keys(stars)
const values = () =>
Object.values(stars)
const entries = () =>
Object.entries(stars)

ðŸŒŧ  Symbol.iterator / @@iterator

stars[Symbol.iterator] = function () {
const latinNames = Object
.values(this)
.map(x => x['🏛'])
let index = 0
return {
next: () => ({
value: latinNames?.[index],
done: ++index > latinNames.length
})
}
}
function forOfLoop() {
const output = []
for (let star of stars) {
output.push(star)
}
return output
}
function arraySpread() {
return [...stars]
}

Google it:

ðŸŒļ addition assignment 🌚 Array every 🌷 Array fill ðŸŒŧ Array forEach 🌞 Array some ðŸŒđ closures 💐 destructuring assignment ðŸŒļ for-break 🌚 for-continue 🌷 for-loop ðŸŒŧ iteration protocols 🌞 Object entries ðŸŒđ Object keys 💐 Object values ðŸŒļ spread rest