Skip to content

Instantly share code, notes, and snippets.

View shawn-dsz's full-sized avatar
🎯
Solving Problems beautifully

Shawn D'Souza shawn-dsz

🎯
Solving Problems beautifully
View GitHub Profile
@shawn-dsz
shawn-dsz / search-tree.ts
Created December 18, 2021 01:06
search nest tree recursive for id
const searchTree = (fn) => (obj) =>
Array.isArray(obj)
? obj.length == 0
? null
: searchTree(fn)(obj[0]) || searchTree(fn)(obj.slice(1))
: fn(
obj,
() => searchTree(fn)(obj.children || []),
() => obj
);
@shawn-dsz
shawn-dsz / getTrues.ts
Last active December 18, 2021 08:16
get object recursive from json
const barr = [
{ id: 1, is: true },
[
{ id: 2, is: false },
[
{ id: 3, is: true },
{ id: 4, is: false },
],
],
];
@shawn-dsz
shawn-dsz / flatten-array-recursively-manually-2.ts
Last active December 18, 2021 01:02
flatten-array-recursively-manually
const foo = [1, [2, [3, 4]]];
// foo.flat(Infinity)
function flatten(a) {
return a.reduce((flat, i) => {
if (Array.isArray(i)) {
return flat.concat(flatten(i));
}
return flat.concat(i);
}, []);
@shawn-dsz
shawn-dsz / maccas.js
Created December 17, 2021 10:17
maccas order (nested tree)
const maccs = [
{
name: 'cheese burger',
type: [
{ name: 'fries', types: [{ name: 'chilli' }, { name: 'chicken salt' }] },
{ name: 'bacon', types: [{ name: 'crispy' }, { name: 'bbq' }] },
{ name: 'sauce', types: [{ name: 'ranch' }, { name: 'soy' }] },
],
},
{
// https://crocoder.dev/blog/map-filter-reduce-exercises/
const input = [1, -4, 12, 0, -3, 29, -150];
input.filter((a) => a > 0).reduce((a, b) => a + b, 0);
const input2 = [12, 46, 32, 64];
const sorted = input2.sort((a, b) => a - b);
const res = sorted.reduce(
@shawn-dsz
shawn-dsz / fib.js
Last active December 17, 2021 01:35
Memoized fib
var memo = {};
const fib = (n) => {
if (n <= 1) return 1;
if (memo[n]) return memo[n];
memo[n] = fib(n - 1) + fib(n - 2)
return memo[n];
};
fib(1);
fib(2);
@shawn-dsz
shawn-dsz / index.js
Created December 17, 2021 00:51
sort alphbetically
const names = ['a', 'b', 'bd', 'bc', 'f'];
const b = names.sort((a, b) => {
if (a < b) return -1;
if (b < a) return 1;
return 0;
});
b;
@shawn-dsz
shawn-dsz / soryBySize.ts
Last active December 17, 2021 00:41
sort object by prop
const files: MyFile[] = [
{ name: 'raz', size: 45, age: 4 },
{ name: 'pop', size: 33, age: 6 },
{ name: 'foo', size: 10, age: 9 },
{ name: 'crackle', size: 21, age: 2 },
{ name: 'baz', size: 22, age: 8 },
{ name: 'bar', size: 15, age: 11 },
];
interface MyFile {
const assert = (v) => {
if (!v) {
throw new Error('False');
}
return true;
};
const groupBy = (arr, fn) =>
arr
.map(typeof fn === 'function' ? fn : (val) => val[fn])
@shawn-dsz
shawn-dsz / groupBy.ts
Last active December 16, 2021 13:36
Implement GroupBy
/**
* Code recipe: Writing JavaScript groupBy() function
*/
// https://sebhastian.com/javascript-group-by/
const movies = [
{ title: 'Sonic the Hedgehog', year: 2020 },
{ title: 'Mulan', year: 2020 },
{ title: 'Godzilla vs. Kong', year: 2021 },