Skip to content

Instantly share code, notes, and snippets.

@CoolOppo
Last active September 2, 2024 16:33
Show Gist options
  • Save CoolOppo/c97799782de3c944390c06c1571d00d7 to your computer and use it in GitHub Desktop.
Save CoolOppo/c97799782de3c944390c06c1571d00d7 to your computer and use it in GitHub Desktop.
/*
* Human Cognitive Thinking Patterns
* =================================
*
* This TypeScript code analogy represents various cognitive thinking patterns
* observed in human thought processes. The patterns included are:
*
* 1. Association
* 2. Categorization
* 3. Pattern Recognition
* 4. Abstraction
* 5. Problem Solving
* 6. Decision Making
* 7. Emotional Processing
* 8. Memory Retrieval
* 9. Creativity
* 10. Metacognition
*
* Each pattern is represented as a class or function, with detailed explanations
* provided in comments. The code aims to capture the essence of these cognitive
* processes using TypeScript analogies, while maintaining readability and
* adhering to best practices.
*/
// Common types and interfaces used throughout the code
type Thought = string;
type Emotion = 'joy' | 'sadness' | 'anger' | 'fear' | 'disgust' | 'surprise';
type Stimulus = any;
interface Memory {
content: Thought;
timestamp: Date;
emotionalContext?: Emotion;
}
/*
* 1. Association
* --------------
* Explanation: Association is the cognitive process of connecting ideas, memories,
* or sensations. It allows humans to form relationships between different concepts
* and experiences, facilitating learning and memory recall.
*
* Pros:
* - Enables rapid information retrieval
* - Supports creative thinking and problem-solving
* - Enhances learning by connecting new information to existing knowledge
*
* Cons:
* - Can lead to biased thinking if associations are overgeneralized
* - May result in false memories or incorrect assumptions
*
* Use cases:
* - Learning new concepts by relating them to familiar ones
* - Recalling information based on contextual cues
* - Forming connections between seemingly unrelated ideas
*/
class Association {
private associationMap: Map<Thought, Set<Thought>> = new Map();
// Associate two thoughts bidirectionally
associate(thought1: Thought, thought2: Thought): void {
this.addAssociation(thought1, thought2);
this.addAssociation(thought2, thought1);
}
// Helper method to add a unidirectional association
private addAssociation(from: Thought, to: Thought): void {
if (!this.associationMap.has(from)) {
this.associationMap.set(from, new Set());
}
this.associationMap.get(from)!.add(to);
}
// Retrieve associated thoughts
getAssociations(thought: Thought): Set<Thought> {
return this.associationMap.get(thought) || new Set();
}
// Example usage
example(): void {
this.associate('apple', 'red');
this.associate('apple', 'fruit');
this.associate('banana', 'fruit');
console.log(this.getAssociations('apple')); // Output: Set { 'red', 'fruit' }
console.log(this.getAssociations('fruit')); // Output: Set { 'apple', 'banana' }
}
}
/*
* 2. Categorization
* -----------------
* Explanation: Categorization is the cognitive process of organizing information,
* objects, or experiences into groups based on shared characteristics. It helps
* humans make sense of the world by simplifying complex information.
*
* Pros:
* - Simplifies information processing
* - Facilitates quick decision-making
* - Supports efficient memory storage and retrieval
*
* Cons:
* - Can lead to stereotyping or overgeneralization
* - May overlook individual differences within categories
*
* Use cases:
* - Organizing knowledge in long-term memory
* - Quickly identifying and responding to environmental stimuli
* - Forming and applying concepts in reasoning and problem-solving
*/
class Categorization {
private categories: Map<string, Set<Thought>> = new Map();
// Categorize a thought
categorize(category: string, thought: Thought): void {
if (!this.categories.has(category)) {
this.categories.set(category, new Set());
}
this.categories.get(category)!.add(thought);
}
// Retrieve thoughts in a category
getCategory(category: string): Set<Thought> {
return this.categories.get(category) || new Set();
}
// Check if a thought belongs to a category
isInCategory(category: string, thought: Thought): boolean {
return this.getCategory(category).has(thought);
}
// Example usage
example(): void {
this.categorize('fruit', 'apple');
this.categorize('fruit', 'banana');
this.categorize('vegetable', 'carrot');
console.log(this.getCategory('fruit')); // Output: Set { 'apple', 'banana' }
console.log(this.isInCategory('fruit', 'apple')); // Output: true
console.log(this.isInCategory('fruit', 'carrot')); // Output: false
}
}
/*
* 3. Pattern Recognition
* ----------------------
* Explanation: Pattern recognition is the cognitive ability to identify regularities,
* trends, or recurring elements in information or experiences. It allows humans to
* make predictions and adapt to their environment.
*
* Pros:
* - Enables quick identification of familiar situations or objects
* - Supports learning and skill acquisition
* - Facilitates problem-solving by recognizing similar past experiences
*
* Cons:
* - Can lead to false pattern detection (apophenia)
* - May result in oversimplification of complex situations
*
* Use cases:
* - Recognizing faces or objects in visual perception
* - Identifying trends in data or behavior
* - Learning and applying rules or regularities in language and communication
*/
class PatternRecognition {
private patterns: Map<string, Array<Stimulus>> = new Map();
// Record a pattern
recordPattern(patternName: string, sequence: Array<Stimulus>): void {
this.patterns.set(patternName, sequence);
}
// Recognize a pattern in a given sequence
recognizePattern(sequence: Array<Stimulus>): string | null {
for (const [patternName, patternSequence] of this.patterns.entries()) {
if (this.isSubsequence(patternSequence, sequence)) {
return patternName;
}
}
return null;
}
// Helper method to check if one sequence is a subsequence of another
private isSubsequence(pattern: Array<Stimulus>, sequence: Array<Stimulus>): boolean {
let patternIndex = 0;
for (const item of sequence) {
if (item === pattern[patternIndex]) {
patternIndex++;
if (patternIndex === pattern.length) {
return true;
}
}
}
return false;
}
// Example usage
example(): void {
this.recordPattern('binary', [0, 1, 0, 1]);
this.recordPattern('ascending', [1, 2, 3, 4]);
console.log(this.recognizePattern([0, 1, 0, 1, 0])); // Output: 'binary'
console.log(this.recognizePattern([0, 1, 2, 3, 4, 5])); // Output: 'ascending'
console.log(this.recognizePattern([5, 4, 3, 2, 1])); // Output: null
}
}
/*
* 4. Abstraction
* --------------
* Explanation: Abstraction is the cognitive process of forming general concepts
* by extracting common features from specific examples. It allows humans to deal
* with complex ideas and generalize knowledge across different contexts.
*
* Pros:
* - Enables efficient processing of complex information
* - Facilitates transfer of knowledge across domains
* - Supports higher-level thinking and problem-solving
*
* Cons:
* - May lead to oversimplification of nuanced situations
* - Can result in loss of important details
*
* Use cases:
* - Forming general concepts from specific instances
* - Applying learned principles to new situations
* - Developing theories and models to explain phenomena
*/
class Abstraction {
private abstractions: Map<string, Set<string>> = new Map();
// Create an abstraction from specific instances
createAbstraction(abstractConcept: string, ...instances: string[]): void {
this.abstractions.set(abstractConcept, new Set(instances));
}
// Add an instance to an existing abstraction
addInstance(abstractConcept: string, instance: string): void {
if (!this.abstractions.has(abstractConcept)) {
this.abstractions.set(abstractConcept, new Set());
}
this.abstractions.get(abstractConcept)!.add(instance);
}
// Check if an instance belongs to an abstraction
isInstanceOf(abstractConcept: string, instance: string): boolean {
return this.abstractions.get(abstractConcept)?.has(instance) || false;
}
// Example usage
example(): void {
this.createAbstraction('Vehicle', 'Car', 'Bicycle', 'Boat');
this.addInstance('Vehicle', 'Airplane');
console.log(this.isInstanceOf('Vehicle', 'Car')); // Output: true
console.log(this.isInstanceOf('Vehicle', 'Airplane')); // Output: true
console.log(this.isInstanceOf('Vehicle', 'House')); // Output: false
}
}
/*
* 5. Problem Solving
* ------------------
* Explanation: Problem solving is the cognitive process of finding solutions to
* challenges or obstacles. It involves identifying the problem, generating
* potential solutions, evaluating options, and implementing the chosen solution.
*
* Pros:
* - Enables overcoming obstacles and achieving goals
* - Promotes critical thinking and creativity
* - Improves decision-making skills
*
* Cons:
* - Can be time-consuming and mentally taxing
* - May lead to analysis paralysis if overused
*
* Use cases:
* - Addressing practical challenges in daily life
* - Solving complex problems in academic or professional settings
* - Developing innovative solutions to societal issues
*/
class ProblemSolving {
// Define a problem-solving strategy
private strategy: (problem: string) => string[];
constructor(strategy: (problem: string) => string[]) {
this.strategy = strategy;
}
// Generate solutions for a given problem
solveProblem(problem: string): string[] {
return this.strategy(problem);
}
// Evaluate and select the best solution
selectBestSolution(solutions: string[]): string {
// In reality, this would involve complex evaluation criteria
return solutions.reduce((best, current) =>
current.length > best.length ? current : best
);
}
// Example usage
example(): void {
const brainstormStrategy = (problem: string): string[] => {
// Simulate brainstorming process
return [
`Solution 1 for ${problem}`,
`Solution 2 for ${problem}`,
`Innovative approach to ${problem}`,
];
};
const problemSolver = new ProblemSolving(brainstormStrategy);
const problem = "How to reduce carbon emissions";
const solutions = problemSolver.solveProblem(problem);
const bestSolution = problemSolver.selectBestSolution(solutions);
console.log("Solutions:", solutions);
console.log("Best solution:", bestSolution);
}
}
/*
* 6. Decision Making
* ------------------
* Explanation: Decision making is the cognitive process of selecting a course
* of action from multiple alternatives. It involves evaluating options based on
* various criteria, considering potential outcomes, and choosing the most
* appropriate action.
*
* Pros:
* - Enables progress and action in the face of uncertainty
* - Can lead to optimal outcomes when done effectively
* - Develops critical thinking and judgment skills
*
* Cons:
* - Can be influenced by cognitive biases
* - May lead to decision fatigue if overused
* - Poor decisions can have negative consequences
*
* Use cases:
* - Making choices in personal and professional life
* - Allocating resources in business or project management
* - Responding to complex situations with multiple options
*/
class DecisionMaking {
// Evaluate options based on given criteria
private evaluateOption(option: string, criteria: string[]): number {
// Simplified evaluation: count how many criteria the option satisfies
return criteria.filter(criterion => option.includes(criterion)).length;
}
// Make a decision based on given options and criteria
makeDecision(options: string[], criteria: string[]): string {
let bestOption = options[0];
let bestScore = this.evaluateOption(bestOption, criteria);
for (const option of options.slice(1)) {
const score = this.evaluateOption(option, criteria);
if (score > bestScore) {
bestOption = option;
bestScore = score;
}
}
return bestOption;
}
// Example usage
example(): void {
const options = [
"Buy a new car",
"Use public transportation",
"Buy a bicycle",
];
const criteria = ["eco-friendly", "cost-effective", "time-saving"];
const decision = this.makeDecision(options, criteria);
console.log("Decision:", decision);
}
}
/*
* 7. Emotional Processing
* -----------------------
* Explanation: Emotional processing is the cognitive and physiological mechanism
* by which humans experience, interpret, and respond to emotions. It involves
* recognizing emotional stimuli, generating emotional responses, and regulating
* emotional states.
*
* Pros:
* - Facilitates social bonding and communication
* - Guides decision-making and behavior
* - Enhances memory formation for significant events
*
* Cons:
* - Can lead to irrational decisions if not properly regulated
* - May cause psychological distress if emotions are overwhelming
* - Can be influenced by cognitive biases and past experiences
*
* Use cases:
* - Responding to environmental threats or opportunities
* - Forming and maintaining social relationships
* - Motivating goal-directed behavior and decision-making
*/
class EmotionalProcessing {
private currentEmotion: Emotion | null = null;
private emotionalMemory: Memory[] = [];
// Process a stimulus and generate an emotional response
processStimulus(stimulus: Stimulus): Emotion {
// Simplified emotional processing based on stimulus characteristics
if (typeof stimulus === 'string' && stimulus.includes('danger')) {
this.currentEmotion = 'fear';
} else if (typeof stimulus === 'number' && stimulus > 0) {
this.currentEmotion = 'joy';
} else {
this.currentEmotion = 'surprise';
}
this.storeEmotionalMemory(stimulus);
return this.currentEmotion;
}
// Store the current emotional state in memory
private storeEmotionalMemory(stimulus: Stimulus): void {
if (this.currentEmotion) {
this.emotionalMemory.push({
content: `Experienced ${this.currentEmotion} in response to ${stimulus}`,
timestamp: new Date(),
emotionalContext: this.currentEmotion,
});
}
}
// Regulate emotional response (simplified version)
regulateEmotion(): void {
if (this.currentEmotion === 'anger' || this.currentEmotion === 'fear') {
console.log("Applying emotion regulation techniques...");
this.currentEmotion = 'neutral';
}
}
// Example usage
example(): void {
console.log(this.processStimulus("Potential danger ahead")); // Output: 'fear'
console.log(this.processStimulus(10)); // Output: 'joy'
this.regulateEmotion();
console.log("Current emotion after regulation:", this.currentEmotion);
}
}
/*
* 8. Memory Retrieval
* -------------------
* Explanation: Memory retrieval is the cognitive process of accessing stored
* information from long-term memory. It involves activating and bringing forth
* previously encoded information in response to cues or as part of thinking
* processes.
*
* Pros:
* - Enables use of past experiences and knowledge in current situations
* - Supports learning and skill development
* - Facilitates problem-solving and decision-making
*
* Cons:
* - Can be influenced by cognitive biases and false memories
* - May lead to over-reliance on past experiences in new situations
* - Retrieval failures (forgetting) can occur
*
* Use cases:
* - Recalling facts and experiences for decision-making
* - Applying learned skills and knowledge
* - Reconstructing past events for storytelling or testimony
*/
class MemoryRetrieval {
private memories: Memory[] = [];
// Store a new memory
storeMemory(content: Thought, emotionalContext?: Emotion): void {
this.memories.push({
content,
timestamp: new Date(),
emotionalContext,
});
}
// Retrieve memories based on content similarity
retrieveMemories(cue: string): Memory[] {
return this.memories.filter(memory =>
memory.content.toLowerCase().includes(cue.toLowerCase())
);
}
// Retrieve memories based on emotional context
retrieveEmotionalMemories(emotion: Emotion): Memory[] {
return this.memories.filter(memory => memory.emotionalContext === emotion);
}
// Example usage
example(): void {
this.storeMemory("Enjoyed a sunny day at the beach", "joy");
this.storeMemory("Learned about memory retrieval processes", "surprise");
this.storeMemory("Felt anxious before an important presentation", "fear");
console.log(this.retrieveMemories("beach"));
console.log(this.retrieveEmotionalMemories("joy"));
}
}
/*
* 9. Creativity
* -------------
* Explanation: Creativity is the cognitive process of generating novel and
* valuable ideas, solutions, or expressions. It involves combining existing
* knowledge and experiences in unique ways to produce original outcomes.
*
* Pros:
* - Leads to innovation and problem-solving
* - Enhances adaptability to new situations
* - Promotes personal growth and self-expression
*
* Cons:
* - Can be unpredictable and difficult to control
* - May lead to impractical or unfeasible ideas
* - Can be inhibited by fear of failure or judgment
*
* Use cases:
* - Developing innovative solutions to complex problems
* - Producing artistic or literary works
* - Generating new ideas in business or scientific research
*/
class Creativity {
private knowledgeBase: Set<string> = new Set();
// Add knowledge to the creative process
addKnowledge(...items: string[]): void {
items.forEach(item => this.knowledgeBase.add(item));
}
// Generate creative ideas by combining existing knowledge
generateIdeas(numIdeas: number): string[] {
const ideas: string[] = [];
const knowledgeArray = Array.from(this.knowledgeBase);
for (let i = 0; i < numIdeas; i++) {
const idea = this.combineRandomElements(knowledgeArray);
ideas.push(idea);
}
return ideas;
}
// Helper method to combine random elements
private combineRandomElements(elements: string[]): string {
const numElements = Math.floor(Math.random() * 3) + 2; // Combine 2-4 elements
const selectedElements = new Set<string>();
while (selectedElements.size < numElements) {
const randomIndex = Math.floor(Math.random() * elements.length);
selectedElements.add(elements[randomIndex]);
}
return Array.from(selectedElements).join(" + ");
}
// Example usage
example(): void {
this.addKnowledge("AI", "art", "music", "sustainability", "education");
const creativeIdeas = this.generateIdeas(3);
console.log("Creative ideas:", creativeIdeas);
}
}
/*
* 10. Metacognition
* -----------------
* Explanation: Metacognition is the awareness and understanding of one's own
* thought processes. It involves monitoring, evaluating, and regulating cognitive
* activities to optimize learning and problem-solving.
*
* Pros:
* - Enhances learning efficiency and effectiveness
* - Improves problem-solving and decision-making skills
* - Promotes self-awareness and personal growth
*
* Cons:
* - Can lead to overthinking or analysis paralysis
* - May be challenging for individuals with certain cognitive disorders
* - Requires mental effort and practice to develop
*
* Use cases:
* - Improving study strategies and learning outcomes
* - Enhancing self-regulation in cognitive tasks
* - Developing more effective problem-solving approaches
*/
class Metacognition {
private strategies: Map<string, (task: string) => void> = new Map();
private taskPerformance: Map<string, number> = new Map();
// Add a cognitive strategy
addStrategy(name: string, strategy: (task: string) => void): void {
this.strategies.set(name, strategy);
}
// Apply a strategy to a task and evaluate its effectiveness
applyStrategy(strategyName: string, task: string): void {
const strategy = this.strategies.get(strategyName);
if (strategy) {
console.log(`Applying strategy "${strategyName}" to task: ${task}`);
strategy(task);
this.evaluatePerformance(strategyName, task);
} else {
console.log(`Strategy "${strategyName}" not found.`);
}
}
// Simulate task performance evaluation
private evaluatePerformance(strategyName: string, task: string): void {
// In reality, this would involve complex performance metrics
const performance = Math.random(); // Simulated performance score
this.taskPerformance.set(`${strategyName}-${task}`, performance);
}
// Reflect on strategy effectiveness
reflectOnStrategies(): void {
for (const [key, performance] of this.taskPerformance.entries()) {
const [strategy, task] = key.split('-');
console.log(`Strategy "${strategy}" for task "${task}": Performance = ${performance.toFixed(2)}`);
}
}
// Example usage
example(): void {
this.addStrategy("Visualization", (task) => {
console.log(`Visualizing ${task} in mind...`);
});
this.addStrategy("Chunking", (task) => {
console.log(`Breaking ${task} into smaller parts...`);
});
this.applyStrategy("Visualization", "complex math problem");
this.applyStrategy("Chunking", "long reading assignment");
this.reflectOnStrategies();
}
}
// Demonstrate the usage of all cognitive thinking patterns
function demonstrateCognitivePatterns(): void {
console.log("1. Association");
new Association().example();
console.log("\n2. Categorization");
new Categorization().example();
console.log("\n3. Pattern Recognition");
new PatternRecognition().example();
console.log("\n4. Abstraction");
new Abstraction().example();
console.log("\n5. Problem Solving");
new ProblemSolving(() => []).example();
console.log("\n6. Decision Making");
new DecisionMaking().example();
console.log("\n7. Emotional Processing");
new EmotionalProcessing().example();
console.log("\n8. Memory Retrieval");
new MemoryRetrieval().example();
console.log("\n9. Creativity");
new Creativity().example();
console.log("\n10. Metacognition");
new Metacognition().example();
}
// Run the demonstration
demonstrateCognitivePatterns();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment