Replies: 17 comments 24 replies
-
function chunk(array, size) {
const chunked = [];
let index = 0;
while (index < array.length) {
chunked.push(array.slice(index, index + size));
index += size;
}
return chunked;
} |
Beta Was this translation helpful? Give feedback.
-
function selectionSort(arr) {
for (let i = 0; i < arr.length; i++) {
let indexOfMin = i;
for (let j = i+1; j <arr.length; j++) {
if (arr[j] < arr[indexOfMin]) {
indexOfMin = j;
}
}
if (indexOfMin !== i) {
let lesser = arr[indexOfMin];
arr[indexOfMin] = arr[i];
arr[i] = lesser;
}
}
return arr;
} |
Beta Was this translation helpful? Give feedback.
-
function mergeSort(arr) {
if (arr.length === 1) {
return arr;
}
const center = Math.floor(arr.length / 2);
const left = arr.slice(0, center);
const right = arr.slice(center);
return merge(mergeSort(left), mergeSort(right));
}
function merge(left, right) {
const results = [];
while (left.length && right.length) {
if (left[0] < right[0]) {
results.push(left.shift());
} else {
results.push(right.shift());
}
}
return [...results, ...left, ...right];
} |
Beta Was this translation helpful? Give feedback.
-
Promises: fetch('https://example.com').then(res => res.text()).then(text => console.log(text)); alternative async/await: const res = await fetch('https://example.com');
const text = await res.text();
console.log(text); |
Beta Was this translation helpful? Give feedback.
-
Generators: function* random(n) {
while (n--) {
yield Math.random();
}
}
for (const num of random(10)) {
console.log(num);
} |
Beta Was this translation helpful? Give feedback.
-
Let's do a little of Typescript: import { useSyncExternalStore } from 'react';
export default function createStore<Shape>(initialState: Shape) {
let currentState = initialState;
const listeners = new Set<(state: Shape) => void>();
let serverState: Shape | null = null;
const subscribe = (listener: (state: Shape) => void) => {
listeners.add(listener);
return () => listeners.delete(listener);
};
return {
getState: () => currentState,
setState: (newState: Shape) => {
currentState = newState;
listeners.forEach((listener) => listener(currentState));
},
subscribe,
serverInitialize: (initialServerState: Shape) => {
if (!serverState) {
currentState = initialServerState;
serverState = initialServerState;
}
},
getServerState: () => serverState ?? initialState,
useStore: <SelectorOutput>(
selector: (state: Shape) => SelectorOutput
): SelectorOutput =>
useSyncExternalStore(
subscribe,
() => selector(currentState),
() => selector(serverState ?? initialState)
),
};
} |
Beta Was this translation helpful? Give feedback.
-
A simple audio player lib in js from my Blog Series let queue = [],
player = new Audio(),
onPlayNext = (url) => ({});
const next = () => playlist(queue, false, false, onPlayNext);
const nextLoop = () => playlist(queue, false, true, onPlayNext);
export const playlist = (
urls,
clear = false,
loop = false,
onNext = onPlayNext
) => {
onPlayNext = onNext;
if (clear) {
queue = [];
queue.push(...urls);
}
if (queue.length !== 0) {
const upcoming = queue.shift();
if (loop) {
queue.push(upcoming);
}
player.src = upcoming;
player.removeEventListener("ended", loop ? nextLoop : next);
player.addEventListener("ended", loop ? nextLoop : next);
player.play();
queue.length && onNext(upcoming);
} else {
player.removeEventListener("ended", loop ? nextLoop : next);
}
};
export const clear = () => {
queue = [];
player.removeEventListener("ended", next);
};
export const play = (url) => {
stop();
player.src = url;
player.play();
};
export const resume = () => {
player.play();
};
export const pause = () => {
player.pause();
};
export const stop = () => {
player.pause();
player.currentTime = 0;
clear();
};
export const onPlay = (action) => {
const cb = () => {
action(player.src);
};
player.addEventListener("play", cb);
return () => player.removeEventListener("play", cb);
};
export const onTimeUpdate = (action) => {
const cb = () => {
action(player.src, player.currentTime);
};
player.addEventListener("timeupdate", cb);
return () => player.removeEventListener("timeupdate", cb);
};
export const onPause = (action) => {
const cb = () => {
action(player.src);
};
player.addEventListener("pause", cb);
return () => player.removeEventListener("pause", cb);
};
export const onStop = (action) => {
const cb = () => {
action(player.src);
};
player.addEventListener("ended", cb);
return () => player.removeEventListener("ended", cb);
}; |
Beta Was this translation helpful? Give feedback.
-
A simple reducer: export const reducer = (state, action) => {
if (action.type === 'ADD_ITEM') {
const newPeople = [...state.people, action.payload];
return {
...state,
people: newPeople,
isModalOpen: true,
modalContent: 'item added',
};
}
if (action.type === 'NO_VALUE') {
return { ...state, isModalOpen: true, modalContent: 'please enter value' };
}
if (action.type === 'CLOSE_MODAL') {
return { ...state, isModalOpen: false };
}
if (action.type === 'REMOVE_ITEM') {
const newPeople = state.people.filter(
(person) => person.id !== action.payload
);
return { ...state, people: newPeople };
}
throw new Error('no matching action type');
}; |
Beta Was this translation helpful? Give feedback.
-
Counting sort: function countingSort(array, min, max) {
let count = new Array(max - min +1).fill(0);
for (let i = 0; i < array.length; i++) {
count[array[i] - min]++;
}
let position = 0;
for (let i = min; i <= max; i++) {
for (let j = 0; j < count[i - min]; j++) {
array[position] = i;
position++;
}
}
return array;
} |
Beta Was this translation helpful? Give feedback.
-
Decimal to Roman: function decimalToRoman(decimal) {
if (decimal < 1 || decimal > 3999) {
return null;
}
const romanNumerals = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1
};
let roman = '';
for (const [numeral, value] of Object.entries(romanNumerals)) {
while (decimal >= value) {
roman += numeral;
decimal -= value;
}
}
return roman;
} |
Beta Was this translation helpful? Give feedback.
-
Using Recursive Depth First Search: var validPath = function(n, edges, source, destination) {
if (source == destination) return true
let adj = Array(n).fill().map(() => [])
let vis = Array(n).fill(false)
for(let i = 0; i < edges.length; i++) {
adj[edges[i][0]].push(edges[i][1])
adj[edges[i][1]].push(edges[i][0])
}
const dfs = (i) => {
if(vis[i]) return false
vis[i] = true
if(i == destination) return true
let res = false
for(let e of adj[i]) res |= dfs(e)
return res
}
return dfs(source)
}; Using Iterative Depth First Search: var validPath = function(n, edges, source, destination) {
if (source == destination) return true
let adj = Array(n).fill().map(() => [])
let vis = Array(n).fill(false)
for(let i = 0; i < edges.length; i++) {
adj[edges[i][0]].push(edges[i][1])
adj[edges[i][1]].push(edges[i][0])
}
const dfs = (source) => {
let stack = [source]
while(stack.length > 0) {
let cur = stack.pop()
if(cur == destination) return true
vis[cur] = true
if(adj[cur])
for(let i of adj[cur]) {
if(vis[i]) continue
stack.push(i)
}
}
return false
}
return dfs(source)
}; |
Beta Was this translation helpful? Give feedback.
-
Binary Search using recursion: const BinarySearch = (arr, x, start, end) => {
if (start > end) return false;
let mid=Math.floor((start + end)/2);
if (arr[mid]===x) return true;
if(arr[mid] > x) return BinarySearch(arr, x, start, mid-1);
else return BinarySearch(arr, x, mid+1, end);
} Binary Search using iteration: const BinarySearch = (arr, x) => {
let start=0, end=arr.length-1;
while (start<=end){
let mid=Math.floor((start + end)/2);
if (arr[mid]===x) return true;
else if (arr[mid] < x)
start = mid + 1;
else
end = mid - 1;
}
return false;
} |
Beta Was this translation helpful? Give feedback.
-
Get a nested property from an object using dot notation! function getPropertyFromObject(obj, path) {
path = path.split(".")
return path.reduce(
(currentValue, currentKey) =>
currentValue && currentValue[currentKey]
? currentValue[currentKey]
: null,
obj
)
} |
Beta Was this translation helpful? Give feedback.
-
Sort array by object field function sortByName (array) {
array.sort((a, b) => {
if (!b.name) {
return 1
}
if (!a.name) {
return -1
}
return a.name.localeCompare(b.name)
})
} |
Beta Was this translation helpful? Give feedback.
-
Using generator as an async function, this is what Babel is doing to async..await when transpiling into generators. function* title() {
var res = yield fetch('https://jcubic.pl/feed.xml');
var text = yield res.text();
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(text, "text/xml");
return xmlDoc.querySelector('title').innerHTML;
}
function is_promise(value) {
return value instanceof Promise ||
(typeof value === 'object' && typeof value.then === 'function');
}
function unwind(gen) {
var iterator = gen()[Symbol.iterator]();
return new Promise(function(resolve) {
(function next(value) {
value = iterator.next(value);
if (!value.done) {
if (is_promise(value.value)) {
value.value.then(next);
} else {
next(value.value);
}
} else {
resolve(value.value);
}
})();
});
}
unwind(title).then((title) => console.log(title)); |
Beta Was this translation helpful? Give feedback.
-
optional async transducer: var compose = function(f, g) {
return function(...args) {
return g(f(...args));
};
};
var resolve = (value, fn) => {
if (value instanceof Promise) {
return value.then(fn);
} else {
return fn(value);
}
};
var map = fn => reducing => (result, input) => {
return reducing(result, resolve(input, fn));
};
var filter = predicate => reducing => (result, input) => {
const next = cond => cond ? reducing(result, input) : result;
return resolve(resolve(input, predicate), next);
}
var connector = fn => (accumulator, element) => {
return resolve(accumulator, (acc) => {
return resolve(element, (e) => fn(acc, e));
});
}
var concat = connector((acc, item) => acc.concat(item));
var sum = connector((a, b) => a + b);
var transducer = compose(map(x => x + 1), filter(x => x % 2 === 0));
(async function() {
var promises = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(n => Promise.resolve(n));
var result = await promises.reduce(transducer(concat), Promise.resolve([]));
console.log(result); // [2, 4, 6, 8, 10]
})();
var result = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
.reduce(transducer(concat), []);
console.log(result); // [2, 4, 6, 8, 10] |
Beta Was this translation helpful? Give feedback.
-
function inherit (Const, Super) {
function F () {}
F.prototype = Super.prototype;
Const.prototype = new F();
Const.prototype.constructor = Const;
} |
Beta Was this translation helpful? Give feedback.
-
One big area of contribution from the community that I would very much appreciate:
Please share here code snippets (preferably in JS) that are substantially (or entirely!) vanilla JS (not just a bunch of React/Vue/etc), or possibly TypeScript. Just focus on snippets that actually illustrate JS syntax (loops, if statements, ternaries, function calls, operators, string interpolations, type coercions, etc).
What I am going for is to be able create more side-by-side examples of code in JS and then the equivalent code in Foi.
Ideally, these snippets will be at least 5-10 lines of code, but probably not longer than about 100 lines of code. Think about the kinds of snippets you'd put in a blog post if you were trying to illustrate some operations/tasks in JS.
Calls to external APIs are fine, so
log()
,fetch()
,setTimeout()
,addEventListener()
, etc... all ok. Just don't focus on snippets that are mostly "boring" abstractions or usages of frameworks/libraries.FOR POSTERITY SAKE, PLEASE COPY/PASTE ACTUAL CODE BELOW, NOT JUST LINKS TO EXTERNAL SOURCES.
Thanks everyone! :)
Beta Was this translation helpful? Give feedback.
All reactions