Skip to content

Instantly share code, notes, and snippets.

View DanShappir's full-sized avatar

Dan Shappir DanShappir

  • Wix
View GitHub Profile
@DanShappir
DanShappir / simple_chain.js
Created November 6, 2019 12:20
JavaScript iteration methods chaining
const result = numbers
.filter(v => v % 2 === 0) // retain only even numbers
.map(v => v + 1) // increase these numbers
.slice(0, 3); // get the first 3 items
@DanShappir
DanShappir / lodash_chain.js
Created November 6, 2019 12:22
lodash chaining
const result2 = _(numbers)
.filter(v => v % 2 === 0) // retain only even numbers
.map(v => v + 1) // increase these numbers
.slice(0, 3) // get the first 3 items
.value();
@DanShappir
DanShappir / map.js
Created November 6, 2019 12:25
Simple map generator
function* map(src, op) {
for (const value of src) {
yield op(value);
}
}
@DanShappir
DanShappir / filter.js
Created November 6, 2019 12:26
Simple filter generator
function* filter(src, op) {
for (const value of src) {
if (op(value)) {
yield value;
}
}
}
@DanShappir
DanShappir / nested.js
Created November 6, 2019 12:27
Operation as nested functions
const result2 = Array.from(
slice(
map(
filter(numbers, v => v % 2 === 0),
v => v + 1
),
0, 3
)
);
@DanShappir
DanShappir / slice.js
Created November 6, 2019 12:28
Simple slice generator
function* slice(src, start, finish = Number.MAX_SAFE_INTEGER) {
let index = 0;
for (const value of src) {
if (index >= finish) {
break;
}
if (index >= start) {
yield value;
}
++index;
@DanShappir
DanShappir / pipeline.js
Created November 6, 2019 12:29
Operation is pipelined functions
const result3 = numbers
|> filter(#, v => v % 2 === 0)
|> map(#, v => v + 1)
|> slice(#, 0, 3)
|> Array.from;
@DanShappir
DanShappir / filter_props.js
Created November 6, 2019 12:30
Filter object properties with pipeline
const retainOnlyNumeric = obj
|> Object.entries
|> filter(#, ([, value]) => typeof value === 'number')
|> Object.fromEntries;
@DanShappir
DanShappir / verbose_find.js
Created November 6, 2019 12:31
Verbose code for implementing find
const largeNumber = numbers
|> filter(#, v => v > 42)
|> slice(#, 0, 1)
|> Array.from
|> (a => a[0])(#);
@DanShappir
DanShappir / head.js
Created November 6, 2019 12:32
Simple head function
function head(src) {
for (const value of src) {
return value;
}
}