const items = {
foo: 1,
bar: 2,
}
function getValueByKey(key) {
return items[key];
}
const items = [
{ key: 'foo', value: 1 },
{ key: 'bar', value: 2 },
]
function getValueByKey(key) {
for (let i = 0; i < items.length; i++) {
const item = items[i];
if (item.key === key) {
return item.value;
}
}
}
--- internal tick
- componentDidMount
- asyncStorage.getItem
- console.log // на этот момент мы ещё не попали в then
--- internal tick
- then блок
- setState
const debounce = ( fn, time ) => {
let timerId;
return ( ...args ) => {
if ( timerId ) {
clearTimeout( timerId );
}
timerId = setTimeout( () => {
fn( ...args );
timerId = null;
}, time );
};
}
const fn = (arg) => {
console.log(arg)
}
const debouncedFn = debounce(fn, 250)
let i = 0
debouncedFn(++i)
debouncedFn(++i)
debouncedFn(++i)
debouncedFn(++i)
function promisify(obj) {
const cache = {}
return new Proxy(obj, {
get(target, prop) {
const value = target[prop]
const type = Object.prototype.toString.call(value)
if (type === '[object Object]') {
if (!cache[prop]) {
cache[prop] = promisify(value)
}
return cache[prop]
} else if (type === '[object Function]') {
if (!cache[prop]) {
cache[prop] = function (...args) {
return new Promise((resolve, reject) => {
const callback = (err, result) => {
if (err) {
reject(err)
} else {
resolve(result)
}
}
value.call(this, callback, ...args)
})
}
}
return cache[prop]
}
return value
},
})
}