Skip to content

Instantly share code, notes, and snippets.

View horiuchie's full-sized avatar
:octocat:

horiuchie horiuchie

:octocat:
View GitHub Profile
@horiuchie
horiuchie / rangeWithStep.js
Created December 11, 2019 08:42
Return a list of numbers [from, to] with step.
const rangeWithStep = (from, to, step=1) => R.map(
i => from + i * step,
R.range(0, 1 + Math.floor((to - from) / step))
);
// Usage
console.log( rangeWithStep(1, 10, 2) ); // [1,3,5,7,9]
console.log( rangeWithStep(53, 92, 11) ); // [53,64,75,86]
@horiuchie
horiuchie / updateOrAppend.js
Created December 11, 2019 08:33
update or append element like get_or_create of Django.
const updateOrAppend = R.curry((comp, value, list) => {
const index = R.findIndex(comp, list);
return index < 0 ? R.append(value, list) : R.update(index, value, list);
});
// Usage
const family = [{ name: 'taro', age: 30 }, { name: 'jiro', age: 28 }, { name: 'saburo', age: 26 }];
// 1. update taro in family if included.
@horiuchie
horiuchie / infiniteCounter.js
Created December 11, 2019 08:08
Infinite counter on Javascript
function infiniteCounter (start=0, step=1) {
const iter = function* () {
let counts = start;
while (true) {
// console.log({ message: counts });
yield counts;
counts += step;
}
}();
return () => iter.next().value;
import Promise from 'bluebird';
Promise.config({ cancellation: true });
const cancellableDelay = (time, cancelHandler) =>
new Promise((resolve, reject, onCancel) => {
const timer = setTimeout(resolve, time);
onCancel(() => {
clearTimeout(timer);
cancelHandler();
});
// https://en.wikipedia.org/wiki/Euclidean_distance
const euclideanDistance = R.compose(
Math.sqrt,
R.sum,
R.zipWith(R.compose(x => x * x, R.subtract))
);
console.log(euclideanDistance([1, 2], [3, 4])); // [x1, y1], [x2, y2]
// 2.8284271247461903
@horiuchie
horiuchie / condition.js
Last active January 5, 2020 15:55
incomplete "pattern matching" in Javascript
import * as R from 'ramda';
const condition = R.unapply(R.toString);
const sameAs = condition;
function viewMode (orientation, layoutNo) {
switch (condition(orientation, layoutNo)) {
case sameAs('portrait', 2):
return 'video and description';
case sameAs('landscape', 1):
@horiuchie
horiuchie / mustBeArray.js
Last active July 31, 2019 02:52
mustBeArray
/*
e.g.
mustBeArray([123, 456, 789]) => [123, 456, 789]
mustBeArray(123) => [123]
*/
const mustBeArray = R.unless(R.is(Array), R.of);
// array type expected
function doSomething (numbers) {
// ...
@horiuchie
horiuchie / renameKeysWith.js
Last active July 31, 2019 02:43
Rename keys with logic of renaming function.
import * as R from 'ramda';
/* オブジェクトのプロタティ名をすべてtransformerに従って変換して返す */
const renameKeysWith = R.curry((transformer, value) => {
if (R.is(Array)(value)) {
return R.map(renameKeysWith(transformer), value);
}
else if (R.is(Object)(value)) {
// [['PropA', valueA], ['PropB', valueB], ...]
const renamedPairs = R.map(