面试题答案
一键面试type StateCallback<T> = (newState: T) => void;
function createStateManager<T>(initialState: T) {
let state: T = initialState;
const callbacks: StateCallback<T>[] = [];
const getState = () => state;
const setState = (newState: T) => {
state = newState;
callbacks.forEach(callback => callback(state));
};
const subscribe = (callback: StateCallback<T>) => {
callbacks.push(callback);
return () => {
const index = callbacks.indexOf(callback);
if (index!== -1) {
callbacks.splice(index, 1);
}
};
};
return {
getState,
setState,
subscribe
};
}
你可以这样使用:
// 使用示例1:数字数组状态
const numberArrayStateManager = createStateManager<number[]>([]);
const unsubscribe1 = numberArrayStateManager.subscribe(newState => {
console.log('数字数组状态变化:', newState);
});
numberArrayStateManager.setState([1, 2, 3]);
unsubscribe1();
// 使用示例2:字符串键值对对象状态
const objectStateManager = createStateManager<{ [key: string]: string }>({});
const unsubscribe2 = objectStateManager.subscribe(newState => {
console.log('对象状态变化:', newState);
});
objectStateManager.setState({ name: 'John' });
unsubscribe2();