Skip to content

Instantly share code, notes, and snippets.

@mrk21
mrk21 / tail-call-optimization.js
Last active September 2, 2019 18:44
Tail call optimization
// @see [Safari 10 supports complete ES2015 which includes Proper Tail Calls](https://medium.com/@dai_shi/safari-10-supports-complete-es2015-which-includes-proper-tail-calls-c8aee33db531)
function f(n, a) {
'use strict';
a = a || 1;
return n == 1 ? a : f(n - 1, a * n);
}
f(1000000); // Safari: OK, Otherwise: Occurs stack level too deep
@mrk21
mrk21 / excel_column_letter.js
Last active September 3, 2019 02:25
Mutually convert column letters and column numbers of Excel
// @see https://leetcode.com/problems/excel-sheet-column-title/description/
const V = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
function fromNumber(n) {
if (n < 1) throw new Error('`n` must be greater than 0');
const v = (n, accum = '') => (
n === 0 ? accum : v(
Math.floor((n-1) / V.length),
V[(n-1) % V.length] + accum
)
@mrk21
mrk21 / config-initializers-trusted_proxies.rb
Created August 31, 2019 10:07
How to get a remote ip on CloudFront + Rails
# @see https://docs.aws.amazon.com/ja_jp/AmazonCloudFront/latest/DeveloperGuide/LocationsOfEdgeServers.html
# @see https://morizyun.github.io/ruby/rails-controller-get-ip.html
# @see https://dev.classmethod.jp/cloud/aws/get-ec2-public-ip-range-by-powershell/
# @see https://github.com/rails/rails/blob/c81af6a/actionpack/lib/action_dispatch/middleware/remote_ip.rb#L112-L150
Rails.application.configure do
ip_ranges_res = Faraday.get('https://ip-ranges.amazonaws.com/ip-ranges.json')
ip_ranges = JSON.parse(ip_ranges_res.body)
cloudfront_ips = ip_ranges['prefixes'].select { |v| v['service'] == 'CLOUDFRONT' }.map { |v| IPAddr.new(v['ip_prefix']) } +
ip_ranges['ipv6_prefixes'].select { |v| v['service'] == 'CLOUDFRONT' }.map { |v| IPAddr.new(v['ipv6_prefix']) }
@mrk21
mrk21 / extract_request_http_headers_for_rails.rb
Last active August 31, 2019 10:01
Extract request HTTP headers for Rails
class ApplicationController < ActionController::Base
private
# @see [Rack::RequestでHTTPリクエストヘッダ一覧を書き出す - Qiita](https://qiita.com/mechamogera/items/9c620155e669b394d513)
# @example
# {
# "Version"=>"HTTP/1.1",
# "Host"=>"localhost:3000",
# "User-Agent"=>"curl/7.54.0",
# "Accept"=>"*/*",
@mrk21
mrk21 / action_typing.ts
Last active July 26, 2019 09:03
TypeScript typings
type ActionTree<T> = {
[ K in keyof T ]: {
type: K;
payload: T[K] extends { payload: any } ? T[K]['payload'] : never;
};
};
type HogeActionTree = ActionTree<{
'hoge/get': {
payload: { id: string; };
@mrk21
mrk21 / entity_store.ts
Last active July 11, 2019 06:35
Typesafe Vuex
import Vue from 'vue';
import { ActionTree, MutationTree, GetterTree } from './type_helper';
import { cloneDeep } from 'lodash';
type Entity = {
value: string
}
type EntityState = {
records: Entity[];
@mrk21
mrk21 / Dockerfile
Created June 13, 2019 06:11
Fluent config sample that outputs logs to stdout, S3 and Cloudwatch Logs
# for development
FROM fluent/fluentd as base
RUN gem install fluent-plugin-s3 -v 1.1.10 --no-document
RUN gem install fluent-plugin-cloudwatch-logs -v 0.7.3 --no-document
# for production
FROM base AS bundle
@mrk21
mrk21 / json_logger.rb
Created June 11, 2019 10:20
JSON logger for Rails
# This logger is having the interface is same to `ActiveSupport::TaggedLogging`.
# @see https://github.com/rails/rails/blob/master/activesupport/lib/active_support/tagged_logging.rb
class JSONLogger < ActiveSupport::Logger
class Formatter < ActiveSupport::Logger::SimpleFormatter
def call severity, timestamp, progname, message
JSON.generate({
type: severity,
time: timestamp.iso8601,
progname: progname,
message: message,
@mrk21
mrk21 / Todo.ts
Last active May 6, 2019 03:17
Generic type gurad for TypeScript
import InvalidValueError from '~/lib/InvalidValueError';
import { PropertyHolder, isNullableType, isNotNullType } from '~/lib/typeHelpers';
export type Todo = {
id: string | null;
title: string;
description: string;
};
export function fromObject(value: unknown): Todo {
@mrk21
mrk21 / using_activerecord_on_migration.rb
Created April 10, 2019 04:35
Using ActiveRecord on migration
class FixHogeTables < ActiveRecord::Migration[5.1]
def change
table(:hoges).where(type: 'bar').each do |hoge|
...
end
end
def table(name)
result = Class.new(ActiveRecord::Base) do
self.table_name = name