Skip to content

Instantly share code, notes, and snippets.

@azendal
Created November 16, 2022 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azendal/27ba975068d7d33239a8c89659217cb3 to your computer and use it in GitHub Desktop.
Save azendal/27ba975068d7d33239a8c89659217cb3 to your computer and use it in GitHub Desktop.
using sets in javascript
// utility fns
var getUid = function(length) {
var i, uid, min, max;
length = length || 32;
uid = '';
min = 0;
max = getUid.codes.length - 1;
for (i = 0; i < length; i++) {
uid += getUid.codes[Math.floor(Math.random() * (max - min + 1)) + min];
}
return uid;
};
getUid.codes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
var benchmark = function (fn) {
return function (...rest) {
var s = Date.now();
var r = fn(rest);
var e = Date.now();
return [r, e - s];
}
};
var byProperty = function (property, value) {
return x => x[property] === value;
}
var randomBetween = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
var randomCase = (cases) => cases[randomBetween(0, cases.length - 1)];
var clamp = (a, min = 0, max = 1) => Math.min(max, Math.max(min, a));
var lerp = (start, end, amt) => (1 - amt) * start + amt * end;
var invLerp = (x, y, a) => clamp((a - x) / (y - x));
var reScale = (o, n, x) => lerp(n[0], n[1], invLerp(o[0], o[1], x));
var log = x => { console.log(x); return x }
var identity = x => x;
var sum = x => x.reduce( (p, c) => p + c, 0 );
var average = x => sum(x) / x.length;
var min = x => x.reduce( (p,c) => Math.min(p,c), Infinity );
var max = x => x.reduce( (p,c) => Math.max(p,c), -Infinity );
var chart = x => console.log('\n' + x.map(x => x.join('')).join('\n') + '\n');
var byNeighborhood = (data, x) => data.filter(h => h.neighborhood == x);
var repeatTimes = (fn, times) => Array.from(Array(times)).map((x, i) => fn(x, i));
var pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x);
var compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x);
var composeAsync = (...fns) => input => fns.reduceRight((chain, func) => chain.then(func), Promise.resolve(input));
var pipeAsync = (...fns) => input => fns.reduce((chain, func) => chain.then(func), Promise.resolve(input));
/*
Filtering functions
This functions return the outcome of a comparison statement
*/
var isNotEmpyString = x => x != '';
var isInAmericana = x => x.neighborhood == 'Americana';
var isInCentro = x => x.neighborhood == 'Centro';
var twoRoomsOrMore = x => x.rooms >= 2;
/*
Maping functions
This functions return a transformed value
*/
var onlyPrice = x => x.price;
var trimString = x => x.trim();
/*
Reducing functions
This functions return a transformed value
*/
var min_ = [(p,c) => Math.min(p,c), Infinity];
var max_ = [(p,c) => Math.max(p,c), -Infinity];
var average_ = [(p,c,i,a) => i === a.length - 1 ? p+c/a.length : p+c, 0];
var neighborhoods_raw = `
Centro
Providencia
Jardines Universidad
La Calma/Pinar
La Estancia
Americana
Santa Teresita
Ciudad Granja
San Pedro Tlaquepaque
Moderna
`;
var neighborhoods = neighborhoods_raw.split('\n').filter(isNotEmpyString).map(trimString);
var buildHouse = function () {
return {
id: getUid(),
neighborhood: randomCase(neighborhoods),
rooms: randomBetween(1,4),
parking: randomBetween(0,3),
price: randomBetween(1000000, 4000000)
}
}
// var data = [
// {id: '89asdjdas897das', neighborhood: 'neighborhood1', rooms:2, parking:0, price: 700000}
//]
var data = Array.from(Array(1000)).map(buildHouse);
console.log('Database')
console.table(data);
//Sets
//https://en.wikipedia.org/wiki/Set_(mathematics)
//In Javascript we have two types of sets
var set = new Set();
var weakSet = new WeakSet();
var realNumbersArr = Array.from(Array(10)).map((x,i) => i);
var realNumbers = new Set(realNumbersArr);
var oddNumbers = new Set(realNumbersArr.filter(x => x%2 > 0));
var evenNumbers = new Set(realNumbersArr.filter(x => x%2 === 0));
console.log('Real Numbers', realNumbers);
console.log('Odd Numbers', oddNumbers);
console.log('Even Numbers', evenNumbers);
console.log('is 0 a real number', realNumbers.has(0));
console.log('is 0 an even number', evenNumbers.has(0));
console.log('is 0 an odd number', oddNumbers.has(0));
var union = (a,b) => new Set([...a, ...b]);
var intersection = (a,b) => new Set([...a].filter(x => b.has(x)));
var difference = (a,b) => new Set([...a].filter(x => !b.has(x)));
var simetricDifference = (a,b) => union(difference(a,b), difference(b,a));
var isSuperSet = (a,b) => [...b].filter(x => !a.has(x)).length == 0;
var isSubSet = (a,b) => [...a].filter(x => !b.has(x)).length == 0;
var areEqualSets = (a,b) => isSuperSet(a,b) && difference(a,b).size === 0;
var unionNumbers = union(oddNumbers, evenNumbers);
console.log('union', unionNumbers)
console.log('O U E = R', areEqualSets(realNumbers, unionNumbers))
console.clear()
console.table(data)
var allHouses = new Set(data);
var housesInAmericana = new Set(data.filter(byProperty('neighborhood', 'Americana')));
var houses1Room = new Set(data.filter(byProperty('rooms', 1)));
var houses1Parking = new Set(data.filter(byProperty('parking', 1)));
// houses in americana and 1 room
console.log( intersection(housesInAmericana, houses1Room) );
// houses in americana and 1 room and 1 parking
console.log( intersection(intersection(housesInAmericana, houses1Parking), houses1Room) );
// houses not in Americana
console.log( difference(allHouses, housesInAmericana) );
// houses not in Americana and 1 room
console.log( intersection(difference(allHouses, housesInAmericana), houses1Room) );
/* IKIGAI */
var activities = [
'traveling',
'resolving issues',
'understand things',
'magic',
'personal development',
'explaining things',
'tv shows',
'movies',
'video games',
'spirituality',
'taking pictures',
'world cultures',
'buddhism',
'helping people',
'making videos',
'teaching',
'explore',
'coaching',
'giving advice',
'web design',
'programming',
'painting',
'sculpting',
'computer graphics',
'math',
'organizing',
'fashion',
'ceramic',
'letherworking',
'hiking',
'woodworking',
'nature',
'science',
'religion',
'psychology',
'people',
'cars',
'running',
'racing',
'skateboarding'
];
var chooseActivities = x => new Set(Array(x).fill(1).map(x => randomCase(activities)));
var activitiesSet = new Set(activities);
var loveSet = chooseActivities(18);
var goodSet = chooseActivities(18);
var needSet = chooseActivities(18);
var paySet = chooseActivities(18);
var loveGood = intersection(loveSet, goodSet);
var loveNeed = intersection(loveSet, needSet);
var goodPay = intersection(goodSet, paySet);
var needPay = intersection(needSet, paySet);
var ikigai = [loveSet, goodSet, needSet, paySet].reduce((a,v) => intersection(a,v), activitiesSet);
console.clear();
console.log('would hate jobs', [...difference(needSet, loveSet)]);
console.log('boring jobs', [...difference(goodSet, loveSet)]);
console.log('hated but rich job', [...difference(difference(goodSet, paySet), loveSet)]);
console.log('would love jobs and have a good time', [...loveGood]);
console.log('would love jobs and make an impact', [...loveNeed]);
console.log('nice pay and have a good time', [...goodPay]);
console.log('nice pay and make and make an impact', [...needPay]);
console.log('The best jobs', ikigai);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment