Skip to content

Instantly share code, notes, and snippets.

View ilanl's full-sized avatar
🚴‍♂️
When not coding...

Ilan Levy ilanl

🚴‍♂️
When not coding...
View GitHub Profile
function reduce(arr, reduceCallback, initialValue) {
if (!Array.isArray(arr) || !arr.length || typeof reduceCallback !== 'function')
{
return [];
} else {
let hasInitialValue = initialValue !== undefined;
let value = hasInitialValue ? initialValue : arr[0];
for (let i = hasInitialValue ? 0 : 1, len = arr.length; i < len; i++) {
value = reduceCallback(value, arr[i], i, arr);
}
function filter(arr, filterCallback) {
if (!Array.isArray(arr) || !arr.length || typeof filterCallback !== 'function')
{
return [];
} else {
let result = [];
for (let i = 0, len = arr.length; i < len; i++) {
if (filterCallback(arr[i], i, arr)) {
result.push(arr[i]);
}
function map(arr, mapCallback) {
if (!Array.isArray(arr) || !arr.length || typeof mapCallback !== 'function') {
return [];
} else {
let result = [];
for (let i = 0, len = arr.length; i < len; i++) {
result.push(mapCallback(arr[i], i, arr));
}
return result;
}
@ilanl
ilanl / up-down-array
Created March 26, 2020 11:21
array up and down
const arr = [ ...Array(100).keys() ].map( i => i+1).sort((a, b) => a-b);
console.log(...arr)
var results = []
while (arr.length > 0) {
results.push(arr.shift())
results.push(arr.pop())
}
console.log(...results)
const delay = t => new Promise(resolve => setTimeout(resolve, t));
@ilanl
ilanl / race-loop
Created February 26, 2020 09:50
threads
```
t1 MEMORY t2
0
read 0 0
inc 1
write 1 1
read 1
inc 2
write 2 2
read 2
@ilanl
ilanl / design-patterns-js
Last active February 22, 2020 18:27
design patterns
// Constructor
function Car( model, year, miles ) {
this.model = model;
this.year = year;
this.miles = miles;
this.toString = function () {
return this.model + " has done " + this.miles + " miles";
@ilanl
ilanl / reduce-count-words
Last active February 22, 2020 13:47
Count Words
function reducer(acc, currentValue, currentIndex, arr) {
acc[currentValue] = (acc[currentValue]+1) || 1;
return acc;
}
function countWords(arrOfWords) {
return arrOfWords.reduce(reducer, {});
}
@ilanl
ilanl / ES6-set-all-map
Created February 20, 2020 17:48
ES6 SetAll Map Override
class MyMap extends Map {
constructor() {
super();
this.counter = 0;
this.all_value = null;
}
set(key, value) {
if (value) {
super.set(key, { ts: this.counter++, v: value });
@ilanl
ilanl / reduce-math
Last active February 22, 2020 10:36
Use Reduce for Math Expression
const exp = '10+2*5*3+6';
const result = exp.split('+').reduce((added, e) => added += (e.split('*').reduce((multiplied, k) => multiplied *= parseInt(k), 1) ), 0 );
console.log(result);