Skip to content

Instantly share code, notes, and snippets.

View fwon's full-sized avatar
🎯
Focusing

Feng Wang fwon

🎯
Focusing
View GitHub Profile
@fwon
fwon / deepClone.js
Created March 30, 2017 07:50
deep clone
function deepClone(obj, hash = new Map()) {
if (Object(obj) !== obj) return obj; // primitives
if (hash.has(obj)) return hash.get(obj); // cyclic reference
var result = Array.isArray(obj) ? []
: obj.constructor ? new obj.constructor() : {};
hash.set(obj, result);
if (obj instanceof Map)
Array.from(obj, ([key, val]) => result.set(key, deepClone(val, hash)) );
return Object.assign(result, ...Object.keys(obj).map (
key => ({ [key]: deepClone(obj[key], hash) }) ));
@fwon
fwon / byte-length.js
Created June 13, 2017 09:38
Get byte length
function getByteLen(normal_val) {
// Force string type
normal_val = String(normal_val);
var byteLen = 0;
for (var i = 0; i < normal_val.length; i++) {
var c = normal_val.charCodeAt(i);
byteLen += c < (1 << 7) ? 1 :
c < (1 << 11) ? 2 :
c < (1 << 16) ? 3 :
@fwon
fwon / useReducer.js
Created April 30, 2020 07:58
hooks reducer
// reducer
function todosReducer(state, action) {
switch (action.type) {
case 'add':
return [...state, {
text: action.text,
completed: false
}];
// ... other actions ...
default: