repo
stringlengths
5
106
file_url
stringlengths
78
301
file_path
stringlengths
4
211
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:56:49
2026-01-05 02:23:25
truncated
bool
2 classes
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/graph/__test__/Graph.test.js
src/data-structures/graph/__test__/Graph.test.js
import Graph from '../Graph'; import GraphVertex from '../GraphVertex'; import GraphEdge from '../GraphEdge'; describe('Graph', () => { it('should add vertices to graph', () => { const graph = new Graph(); const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); graph .addVertex(vertexA) .addVertex(vertexB); expect(graph.toString()).toBe('A,B'); expect(graph.getVertexByKey(vertexA.getKey())).toEqual(vertexA); expect(graph.getVertexByKey(vertexB.getKey())).toEqual(vertexB); }); it('should add edges to undirected graph', () => { const graph = new Graph(); const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); const edgeAB = new GraphEdge(vertexA, vertexB); graph.addEdge(edgeAB); expect(graph.getAllVertices().length).toBe(2); expect(graph.getAllVertices()[0]).toEqual(vertexA); expect(graph.getAllVertices()[1]).toEqual(vertexB); const graphVertexA = graph.getVertexByKey(vertexA.getKey()); const graphVertexB = graph.getVertexByKey(vertexB.getKey()); expect(graph.toString()).toBe('A,B'); expect(graphVertexA).toBeDefined(); expect(graphVertexB).toBeDefined(); expect(graph.getVertexByKey('not existing')).toBeUndefined(); expect(graphVertexA.getNeighbors().length).toBe(1); expect(graphVertexA.getNeighbors()[0]).toEqual(vertexB); expect(graphVertexA.getNeighbors()[0]).toEqual(graphVertexB); expect(graphVertexB.getNeighbors().length).toBe(1); expect(graphVertexB.getNeighbors()[0]).toEqual(vertexA); expect(graphVertexB.getNeighbors()[0]).toEqual(graphVertexA); }); it('should add edges to directed graph', () => { const graph = new Graph(true); const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); const edgeAB = new GraphEdge(vertexA, vertexB); graph.addEdge(edgeAB); const graphVertexA = graph.getVertexByKey(vertexA.getKey()); const graphVertexB = graph.getVertexByKey(vertexB.getKey()); expect(graph.toString()).toBe('A,B'); expect(graphVertexA).toBeDefined(); expect(graphVertexB).toBeDefined(); expect(graphVertexA.getNeighbors().length).toBe(1); expect(graphVertexA.getNeighbors()[0]).toEqual(vertexB); expect(graphVertexA.getNeighbors()[0]).toEqual(graphVertexB); expect(graphVertexB.getNeighbors().length).toBe(0); }); it('should find edge by vertices in undirected graph', () => { const graph = new Graph(); const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); const vertexC = new GraphVertex('C'); const edgeAB = new GraphEdge(vertexA, vertexB, 10); graph.addEdge(edgeAB); const graphEdgeAB = graph.findEdge(vertexA, vertexB); const graphEdgeBA = graph.findEdge(vertexB, vertexA); const graphEdgeAC = graph.findEdge(vertexA, vertexC); const graphEdgeCA = graph.findEdge(vertexC, vertexA); expect(graphEdgeAC).toBeNull(); expect(graphEdgeCA).toBeNull(); expect(graphEdgeAB).toEqual(edgeAB); expect(graphEdgeBA).toEqual(edgeAB); expect(graphEdgeAB.weight).toBe(10); }); it('should find edge by vertices in directed graph', () => { const graph = new Graph(true); const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); const vertexC = new GraphVertex('C'); const edgeAB = new GraphEdge(vertexA, vertexB, 10); graph.addEdge(edgeAB); const graphEdgeAB = graph.findEdge(vertexA, vertexB); const graphEdgeBA = graph.findEdge(vertexB, vertexA); const graphEdgeAC = graph.findEdge(vertexA, vertexC); const graphEdgeCA = graph.findEdge(vertexC, vertexA); expect(graphEdgeAC).toBeNull(); expect(graphEdgeCA).toBeNull(); expect(graphEdgeBA).toBeNull(); expect(graphEdgeAB).toEqual(edgeAB); expect(graphEdgeAB.weight).toBe(10); }); it('should return vertex neighbors', () => { const graph = new Graph(true); const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); const vertexC = new GraphVertex('C'); const edgeAB = new GraphEdge(vertexA, vertexB); const edgeAC = new GraphEdge(vertexA, vertexC); graph .addEdge(edgeAB) .addEdge(edgeAC); const neighbors = graph.getNeighbors(vertexA); expect(neighbors.length).toBe(2); expect(neighbors[0]).toEqual(vertexB); expect(neighbors[1]).toEqual(vertexC); }); it('should throw an error when trying to add edge twice', () => { function addSameEdgeTwice() { const graph = new Graph(true); const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); const edgeAB = new GraphEdge(vertexA, vertexB); graph .addEdge(edgeAB) .addEdge(edgeAB); } expect(addSameEdgeTwice).toThrow(); }); it('should throw an error when trying to add vertex twice', () => { function addSameEdgeTwice() { const graph = new Graph(true); const vertexA = new GraphVertex('A'); graph .addVertex(vertexA) .addVertex(vertexA); } expect(addSameEdgeTwice).toThrow(); }); it('should return the list of all added edges', () => { const graph = new Graph(true); const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); const vertexC = new GraphVertex('C'); const edgeAB = new GraphEdge(vertexA, vertexB); const edgeBC = new GraphEdge(vertexB, vertexC); graph .addEdge(edgeAB) .addEdge(edgeBC); const edges = graph.getAllEdges(); expect(edges.length).toBe(2); expect(edges[0]).toEqual(edgeAB); expect(edges[1]).toEqual(edgeBC); }); it('should calculate total graph weight for default graph', () => { const graph = new Graph(); const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); const vertexC = new GraphVertex('C'); const vertexD = new GraphVertex('D'); const edgeAB = new GraphEdge(vertexA, vertexB); const edgeBC = new GraphEdge(vertexB, vertexC); const edgeCD = new GraphEdge(vertexC, vertexD); const edgeAD = new GraphEdge(vertexA, vertexD); graph .addEdge(edgeAB) .addEdge(edgeBC) .addEdge(edgeCD) .addEdge(edgeAD); expect(graph.getWeight()).toBe(0); }); it('should calculate total graph weight for weighted graph', () => { const graph = new Graph(); const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); const vertexC = new GraphVertex('C'); const vertexD = new GraphVertex('D'); const edgeAB = new GraphEdge(vertexA, vertexB, 1); const edgeBC = new GraphEdge(vertexB, vertexC, 2); const edgeCD = new GraphEdge(vertexC, vertexD, 3); const edgeAD = new GraphEdge(vertexA, vertexD, 4); graph .addEdge(edgeAB) .addEdge(edgeBC) .addEdge(edgeCD) .addEdge(edgeAD); expect(graph.getWeight()).toBe(10); }); it('should be possible to delete edges from graph', () => { const graph = new Graph(); const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); const vertexC = new GraphVertex('C'); const edgeAB = new GraphEdge(vertexA, vertexB); const edgeBC = new GraphEdge(vertexB, vertexC); const edgeAC = new GraphEdge(vertexA, vertexC); graph .addEdge(edgeAB) .addEdge(edgeBC) .addEdge(edgeAC); expect(graph.getAllEdges().length).toBe(3); graph.deleteEdge(edgeAB); expect(graph.getAllEdges().length).toBe(2); expect(graph.getAllEdges()[0].getKey()).toBe(edgeBC.getKey()); expect(graph.getAllEdges()[1].getKey()).toBe(edgeAC.getKey()); }); it('should should throw an error when trying to delete not existing edge', () => { function deleteNotExistingEdge() { const graph = new Graph(); const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); const vertexC = new GraphVertex('C'); const edgeAB = new GraphEdge(vertexA, vertexB); const edgeBC = new GraphEdge(vertexB, vertexC); graph.addEdge(edgeAB); graph.deleteEdge(edgeBC); } expect(deleteNotExistingEdge).toThrowError(); }); it('should be possible to reverse graph', () => { const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); const vertexC = new GraphVertex('C'); const vertexD = new GraphVertex('D'); const edgeAB = new GraphEdge(vertexA, vertexB); const edgeAC = new GraphEdge(vertexA, vertexC); const edgeCD = new GraphEdge(vertexC, vertexD); const graph = new Graph(true); graph .addEdge(edgeAB) .addEdge(edgeAC) .addEdge(edgeCD); expect(graph.toString()).toBe('A,B,C,D'); expect(graph.getAllEdges().length).toBe(3); expect(graph.getNeighbors(vertexA).length).toBe(2); expect(graph.getNeighbors(vertexA)[0].getKey()).toBe(vertexB.getKey()); expect(graph.getNeighbors(vertexA)[1].getKey()).toBe(vertexC.getKey()); expect(graph.getNeighbors(vertexB).length).toBe(0); expect(graph.getNeighbors(vertexC).length).toBe(1); expect(graph.getNeighbors(vertexC)[0].getKey()).toBe(vertexD.getKey()); expect(graph.getNeighbors(vertexD).length).toBe(0); graph.reverse(); expect(graph.toString()).toBe('A,B,C,D'); expect(graph.getAllEdges().length).toBe(3); expect(graph.getNeighbors(vertexA).length).toBe(0); expect(graph.getNeighbors(vertexB).length).toBe(1); expect(graph.getNeighbors(vertexB)[0].getKey()).toBe(vertexA.getKey()); expect(graph.getNeighbors(vertexC).length).toBe(1); expect(graph.getNeighbors(vertexC)[0].getKey()).toBe(vertexA.getKey()); expect(graph.getNeighbors(vertexD).length).toBe(1); expect(graph.getNeighbors(vertexD)[0].getKey()).toBe(vertexC.getKey()); }); it('should return vertices indices', () => { const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); const vertexC = new GraphVertex('C'); const vertexD = new GraphVertex('D'); const edgeAB = new GraphEdge(vertexA, vertexB); const edgeBC = new GraphEdge(vertexB, vertexC); const edgeCD = new GraphEdge(vertexC, vertexD); const edgeBD = new GraphEdge(vertexB, vertexD); const graph = new Graph(); graph .addEdge(edgeAB) .addEdge(edgeBC) .addEdge(edgeCD) .addEdge(edgeBD); const verticesIndices = graph.getVerticesIndices(); expect(verticesIndices).toEqual({ A: 0, B: 1, C: 2, D: 3, }); }); it('should generate adjacency matrix for undirected graph', () => { const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); const vertexC = new GraphVertex('C'); const vertexD = new GraphVertex('D'); const edgeAB = new GraphEdge(vertexA, vertexB); const edgeBC = new GraphEdge(vertexB, vertexC); const edgeCD = new GraphEdge(vertexC, vertexD); const edgeBD = new GraphEdge(vertexB, vertexD); const graph = new Graph(); graph .addEdge(edgeAB) .addEdge(edgeBC) .addEdge(edgeCD) .addEdge(edgeBD); const adjacencyMatrix = graph.getAdjacencyMatrix(); expect(adjacencyMatrix).toEqual([ [Infinity, 0, Infinity, Infinity], [0, Infinity, 0, 0], [Infinity, 0, Infinity, 0], [Infinity, 0, 0, Infinity], ]); }); it('should generate adjacency matrix for directed graph', () => { const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); const vertexC = new GraphVertex('C'); const vertexD = new GraphVertex('D'); const edgeAB = new GraphEdge(vertexA, vertexB, 2); const edgeBC = new GraphEdge(vertexB, vertexC, 1); const edgeCD = new GraphEdge(vertexC, vertexD, 5); const edgeBD = new GraphEdge(vertexB, vertexD, 7); const graph = new Graph(true); graph .addEdge(edgeAB) .addEdge(edgeBC) .addEdge(edgeCD) .addEdge(edgeBD); const adjacencyMatrix = graph.getAdjacencyMatrix(); expect(adjacencyMatrix).toEqual([ [Infinity, 2, Infinity, Infinity], [Infinity, Infinity, 1, 7], [Infinity, Infinity, Infinity, 5], [Infinity, Infinity, Infinity, Infinity], ]); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/graph/__test__/GraphVertex.test.js
src/data-structures/graph/__test__/GraphVertex.test.js
import GraphVertex from '../GraphVertex'; import GraphEdge from '../GraphEdge'; describe('GraphVertex', () => { it('should throw an error when trying to create vertex without value', () => { let vertex = null; function createEmptyVertex() { vertex = new GraphVertex(); } expect(vertex).toBeNull(); expect(createEmptyVertex).toThrow(); }); it('should create graph vertex', () => { const vertex = new GraphVertex('A'); expect(vertex).toBeDefined(); expect(vertex.value).toBe('A'); expect(vertex.toString()).toBe('A'); expect(vertex.getKey()).toBe('A'); expect(vertex.edges.toString()).toBe(''); expect(vertex.getEdges()).toEqual([]); }); it('should add edges to vertex and check if it exists', () => { const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); const edgeAB = new GraphEdge(vertexA, vertexB); vertexA.addEdge(edgeAB); expect(vertexA.hasEdge(edgeAB)).toBe(true); expect(vertexB.hasEdge(edgeAB)).toBe(false); expect(vertexA.getEdges().length).toBe(1); expect(vertexA.getEdges()[0].toString()).toBe('A_B'); }); it('should delete edges from vertex', () => { const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); const vertexC = new GraphVertex('C'); const edgeAB = new GraphEdge(vertexA, vertexB); const edgeAC = new GraphEdge(vertexA, vertexC); vertexA .addEdge(edgeAB) .addEdge(edgeAC); expect(vertexA.hasEdge(edgeAB)).toBe(true); expect(vertexB.hasEdge(edgeAB)).toBe(false); expect(vertexA.hasEdge(edgeAC)).toBe(true); expect(vertexC.hasEdge(edgeAC)).toBe(false); expect(vertexA.getEdges().length).toBe(2); expect(vertexA.getEdges()[0].toString()).toBe('A_B'); expect(vertexA.getEdges()[1].toString()).toBe('A_C'); vertexA.deleteEdge(edgeAB); expect(vertexA.hasEdge(edgeAB)).toBe(false); expect(vertexA.hasEdge(edgeAC)).toBe(true); expect(vertexA.getEdges()[0].toString()).toBe('A_C'); vertexA.deleteEdge(edgeAC); expect(vertexA.hasEdge(edgeAB)).toBe(false); expect(vertexA.hasEdge(edgeAC)).toBe(false); expect(vertexA.getEdges().length).toBe(0); }); it('should delete all edges from vertex', () => { const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); const vertexC = new GraphVertex('C'); const edgeAB = new GraphEdge(vertexA, vertexB); const edgeAC = new GraphEdge(vertexA, vertexC); vertexA .addEdge(edgeAB) .addEdge(edgeAC); expect(vertexA.hasEdge(edgeAB)).toBe(true); expect(vertexB.hasEdge(edgeAB)).toBe(false); expect(vertexA.hasEdge(edgeAC)).toBe(true); expect(vertexC.hasEdge(edgeAC)).toBe(false); expect(vertexA.getEdges().length).toBe(2); vertexA.deleteAllEdges(); expect(vertexA.hasEdge(edgeAB)).toBe(false); expect(vertexB.hasEdge(edgeAB)).toBe(false); expect(vertexA.hasEdge(edgeAC)).toBe(false); expect(vertexC.hasEdge(edgeAC)).toBe(false); expect(vertexA.getEdges().length).toBe(0); }); it('should return vertex neighbors in case if current node is start one', () => { const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); const vertexC = new GraphVertex('C'); const edgeAB = new GraphEdge(vertexA, vertexB); const edgeAC = new GraphEdge(vertexA, vertexC); vertexA .addEdge(edgeAB) .addEdge(edgeAC); expect(vertexB.getNeighbors()).toEqual([]); const neighbors = vertexA.getNeighbors(); expect(neighbors.length).toBe(2); expect(neighbors[0]).toEqual(vertexB); expect(neighbors[1]).toEqual(vertexC); }); it('should return vertex neighbors in case if current node is end one', () => { const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); const vertexC = new GraphVertex('C'); const edgeBA = new GraphEdge(vertexB, vertexA); const edgeCA = new GraphEdge(vertexC, vertexA); vertexA .addEdge(edgeBA) .addEdge(edgeCA); expect(vertexB.getNeighbors()).toEqual([]); const neighbors = vertexA.getNeighbors(); expect(neighbors.length).toBe(2); expect(neighbors[0]).toEqual(vertexB); expect(neighbors[1]).toEqual(vertexC); }); it('should check if vertex has specific neighbor', () => { const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); const vertexC = new GraphVertex('C'); const edgeAB = new GraphEdge(vertexA, vertexB); vertexA.addEdge(edgeAB); expect(vertexA.hasNeighbor(vertexB)).toBe(true); expect(vertexA.hasNeighbor(vertexC)).toBe(false); }); it('should edge by vertex', () => { const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); const vertexC = new GraphVertex('C'); const edgeAB = new GraphEdge(vertexA, vertexB); vertexA.addEdge(edgeAB); expect(vertexA.findEdge(vertexB)).toEqual(edgeAB); expect(vertexA.findEdge(vertexC)).toBeNull(); }); it('should calculate vertex degree', () => { const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B'); expect(vertexA.getDegree()).toBe(0); const edgeAB = new GraphEdge(vertexA, vertexB); vertexA.addEdge(edgeAB); expect(vertexA.getDegree()).toBe(1); const edgeBA = new GraphEdge(vertexB, vertexA); vertexA.addEdge(edgeBA); expect(vertexA.getDegree()).toBe(2); vertexA.addEdge(edgeAB); expect(vertexA.getDegree()).toBe(3); expect(vertexA.getEdges().length).toEqual(3); }); it('should execute callback when passed to toString', () => { const vertex = new GraphVertex('A'); expect(vertex.toString(() => 'B')).toEqual('B'); }); it('should execute toString on value when calling toString on vertex', () => { const value = { toString() { return 'A'; }, }; const vertex = new GraphVertex(value); expect(vertex.toString()).toEqual('A'); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/priority-queue/PriorityQueue.js
src/data-structures/priority-queue/PriorityQueue.js
import MinHeap from '../heap/MinHeap'; import Comparator from '../../utils/comparator/Comparator'; // It is the same as min heap except that when comparing two elements // we take into account its priority instead of the element's value. export default class PriorityQueue extends MinHeap { constructor() { // Call MinHip constructor first. super(); // Setup priorities map. this.priorities = new Map(); // Use custom comparator for heap elements that will take element priority // instead of element value into account. this.compare = new Comparator(this.comparePriority.bind(this)); } /** * Add item to the priority queue. * @param {*} item - item we're going to add to the queue. * @param {number} [priority] - items priority. * @return {PriorityQueue} */ add(item, priority = 0) { this.priorities.set(item, priority); super.add(item); return this; } /** * Remove item from priority queue. * @param {*} item - item we're going to remove. * @param {Comparator} [customFindingComparator] - custom function for finding the item to remove * @return {PriorityQueue} */ remove(item, customFindingComparator) { super.remove(item, customFindingComparator); this.priorities.delete(item); return this; } /** * Change priority of the item in a queue. * @param {*} item - item we're going to re-prioritize. * @param {number} priority - new item's priority. * @return {PriorityQueue} */ changePriority(item, priority) { this.remove(item, new Comparator(this.compareValue)); this.add(item, priority); return this; } /** * Find item by ite value. * @param {*} item * @return {Number[]} */ findByValue(item) { return this.find(item, new Comparator(this.compareValue)); } /** * Check if item already exists in a queue. * @param {*} item * @return {boolean} */ hasValue(item) { return this.findByValue(item).length > 0; } /** * Compares priorities of two items. * @param {*} a * @param {*} b * @return {number} */ comparePriority(a, b) { if (this.priorities.get(a) === this.priorities.get(b)) { return 0; } return this.priorities.get(a) < this.priorities.get(b) ? -1 : 1; } /** * Compares values of two items. * @param {*} a * @param {*} b * @return {number} */ compareValue(a, b) { if (a === b) { return 0; } return a < b ? -1 : 1; } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/priority-queue/__test__/PriorityQueue.test.js
src/data-structures/priority-queue/__test__/PriorityQueue.test.js
import PriorityQueue from '../PriorityQueue'; describe('PriorityQueue', () => { it('should create default priority queue', () => { const priorityQueue = new PriorityQueue(); expect(priorityQueue).toBeDefined(); }); it('should insert items to the queue and respect priorities', () => { const priorityQueue = new PriorityQueue(); priorityQueue.add(10, 1); expect(priorityQueue.peek()).toBe(10); priorityQueue.add(5, 2); expect(priorityQueue.peek()).toBe(10); priorityQueue.add(100, 0); expect(priorityQueue.peek()).toBe(100); }); it('should be possible to use objects in priority queue', () => { const priorityQueue = new PriorityQueue(); const user1 = { name: 'Mike' }; const user2 = { name: 'Bill' }; const user3 = { name: 'Jane' }; priorityQueue.add(user1, 1); expect(priorityQueue.peek()).toBe(user1); priorityQueue.add(user2, 2); expect(priorityQueue.peek()).toBe(user1); priorityQueue.add(user3, 0); expect(priorityQueue.peek()).toBe(user3); }); it('should poll from queue with respect to priorities', () => { const priorityQueue = new PriorityQueue(); priorityQueue.add(10, 1); priorityQueue.add(5, 2); priorityQueue.add(100, 0); priorityQueue.add(200, 0); expect(priorityQueue.poll()).toBe(100); expect(priorityQueue.poll()).toBe(200); expect(priorityQueue.poll()).toBe(10); expect(priorityQueue.poll()).toBe(5); }); it('should be possible to change priority of head node', () => { const priorityQueue = new PriorityQueue(); priorityQueue.add(10, 1); priorityQueue.add(5, 2); priorityQueue.add(100, 0); priorityQueue.add(200, 0); expect(priorityQueue.peek()).toBe(100); priorityQueue.changePriority(100, 10); priorityQueue.changePriority(10, 20); expect(priorityQueue.poll()).toBe(200); expect(priorityQueue.poll()).toBe(5); expect(priorityQueue.poll()).toBe(100); expect(priorityQueue.poll()).toBe(10); }); it('should be possible to change priority of internal nodes', () => { const priorityQueue = new PriorityQueue(); priorityQueue.add(10, 1); priorityQueue.add(5, 2); priorityQueue.add(100, 0); priorityQueue.add(200, 0); expect(priorityQueue.peek()).toBe(100); priorityQueue.changePriority(200, 10); priorityQueue.changePriority(10, 20); expect(priorityQueue.poll()).toBe(100); expect(priorityQueue.poll()).toBe(5); expect(priorityQueue.poll()).toBe(200); expect(priorityQueue.poll()).toBe(10); }); it('should be possible to change priority along with node addition', () => { const priorityQueue = new PriorityQueue(); priorityQueue.add(10, 1); priorityQueue.add(5, 2); priorityQueue.add(100, 0); priorityQueue.add(200, 0); priorityQueue.changePriority(200, 10); priorityQueue.changePriority(10, 20); priorityQueue.add(15, 15); expect(priorityQueue.poll()).toBe(100); expect(priorityQueue.poll()).toBe(5); expect(priorityQueue.poll()).toBe(200); expect(priorityQueue.poll()).toBe(15); expect(priorityQueue.poll()).toBe(10); }); it('should be possible to search in priority queue by value', () => { const priorityQueue = new PriorityQueue(); priorityQueue.add(10, 1); priorityQueue.add(5, 2); priorityQueue.add(100, 0); priorityQueue.add(200, 0); priorityQueue.add(15, 15); expect(priorityQueue.hasValue(70)).toBe(false); expect(priorityQueue.hasValue(15)).toBe(true); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/linked-list/LinkedList.js
src/data-structures/linked-list/LinkedList.js
import LinkedListNode from './LinkedListNode'; import Comparator from '../../utils/comparator/Comparator'; export default class LinkedList { /** * @param {Function} [comparatorFunction] */ constructor(comparatorFunction) { /** @var LinkedListNode */ this.head = null; /** @var LinkedListNode */ this.tail = null; this.compare = new Comparator(comparatorFunction); } /** * @param {*} value * @return {LinkedList} */ prepend(value) { // Make new node to be a head. const newNode = new LinkedListNode(value, this.head); this.head = newNode; // If there is no tail yet let's make new node a tail. if (!this.tail) { this.tail = newNode; } return this; } /** * @param {*} value * @return {LinkedList} */ append(value) { const newNode = new LinkedListNode(value); // If there is no head yet let's make new node a head. if (!this.head) { this.head = newNode; this.tail = newNode; return this; } // Attach new node to the end of linked list. this.tail.next = newNode; this.tail = newNode; return this; } /** * @param {*} value * @param {number} index * @return {LinkedList} */ insert(value, rawIndex) { const index = rawIndex < 0 ? 0 : rawIndex; if (index === 0) { this.prepend(value); } else { let count = 1; let currentNode = this.head; const newNode = new LinkedListNode(value); while (currentNode) { if (count === index) break; currentNode = currentNode.next; count += 1; } if (currentNode) { newNode.next = currentNode.next; currentNode.next = newNode; } else { if (this.tail) { this.tail.next = newNode; this.tail = newNode; } else { this.head = newNode; this.tail = newNode; } } } return this; } /** * @param {*} value * @return {LinkedListNode} */ delete(value) { if (!this.head) { return null; } let deletedNode = null; // If the head must be deleted then make next node that is different // from the head to be a new head. while (this.head && this.compare.equal(this.head.value, value)) { deletedNode = this.head; this.head = this.head.next; } let currentNode = this.head; if (currentNode !== null) { // If next node must be deleted then make next node to be a next next one. while (currentNode.next) { if (this.compare.equal(currentNode.next.value, value)) { deletedNode = currentNode.next; currentNode.next = currentNode.next.next; } else { currentNode = currentNode.next; } } } // Check if tail must be deleted. if (this.compare.equal(this.tail.value, value)) { this.tail = currentNode; } return deletedNode; } /** * @param {Object} findParams * @param {*} findParams.value * @param {function} [findParams.callback] * @return {LinkedListNode} */ find({ value = undefined, callback = undefined }) { if (!this.head) { return null; } let currentNode = this.head; while (currentNode) { // If callback is specified then try to find node by callback. if (callback && callback(currentNode.value)) { return currentNode; } // If value is specified then try to compare by value.. if (value !== undefined && this.compare.equal(currentNode.value, value)) { return currentNode; } currentNode = currentNode.next; } return null; } /** * @return {LinkedListNode} */ deleteTail() { const deletedTail = this.tail; if (this.head === this.tail) { // There is only one node in linked list. this.head = null; this.tail = null; return deletedTail; } // If there are many nodes in linked list... // Rewind to the last node and delete "next" link for the node before the last one. let currentNode = this.head; while (currentNode.next) { if (!currentNode.next.next) { currentNode.next = null; } else { currentNode = currentNode.next; } } this.tail = currentNode; return deletedTail; } /** * @return {LinkedListNode} */ deleteHead() { if (!this.head) { return null; } const deletedHead = this.head; if (this.head.next) { this.head = this.head.next; } else { this.head = null; this.tail = null; } return deletedHead; } /** * @param {*[]} values - Array of values that need to be converted to linked list. * @return {LinkedList} */ fromArray(values) { values.forEach((value) => this.append(value)); return this; } /** * @return {LinkedListNode[]} */ toArray() { const nodes = []; let currentNode = this.head; while (currentNode) { nodes.push(currentNode); currentNode = currentNode.next; } return nodes; } /** * @param {function} [callback] * @return {string} */ toString(callback) { return this.toArray().map((node) => node.toString(callback)).toString(); } /** * Reverse a linked list. * @returns {LinkedList} */ reverse() { let currNode = this.head; let prevNode = null; let nextNode = null; while (currNode) { // Store next node. nextNode = currNode.next; // Change next node of the current node so it would link to previous node. currNode.next = prevNode; // Move prevNode and currNode nodes one step forward. prevNode = currNode; currNode = nextNode; } // Reset head and tail. this.tail = this.head; this.head = prevNode; return this; } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/linked-list/LinkedListNode.js
src/data-structures/linked-list/LinkedListNode.js
export default class LinkedListNode { constructor(value, next = null) { this.value = value; this.next = next; } toString(callback) { return callback ? callback(this.value) : `${this.value}`; } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/linked-list/__test__/LinkedListNode.test.js
src/data-structures/linked-list/__test__/LinkedListNode.test.js
import LinkedListNode from '../LinkedListNode'; describe('LinkedListNode', () => { it('should create list node with value', () => { const node = new LinkedListNode(1); expect(node.value).toBe(1); expect(node.next).toBeNull(); }); it('should create list node with object as a value', () => { const nodeValue = { value: 1, key: 'test' }; const node = new LinkedListNode(nodeValue); expect(node.value.value).toBe(1); expect(node.value.key).toBe('test'); expect(node.next).toBeNull(); }); it('should link nodes together', () => { const node2 = new LinkedListNode(2); const node1 = new LinkedListNode(1, node2); expect(node1.next).toBeDefined(); expect(node2.next).toBeNull(); expect(node1.value).toBe(1); expect(node1.next.value).toBe(2); }); it('should convert node to string', () => { const node = new LinkedListNode(1); expect(node.toString()).toBe('1'); node.value = 'string value'; expect(node.toString()).toBe('string value'); }); it('should convert node to string with custom stringifier', () => { const nodeValue = { value: 1, key: 'test' }; const node = new LinkedListNode(nodeValue); const toStringCallback = (value) => `value: ${value.value}, key: ${value.key}`; expect(node.toString(toStringCallback)).toBe('value: 1, key: test'); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/linked-list/__test__/LinkedList.test.js
src/data-structures/linked-list/__test__/LinkedList.test.js
import LinkedList from '../LinkedList'; describe('LinkedList', () => { it('should create empty linked list', () => { const linkedList = new LinkedList(); expect(linkedList.toString()).toBe(''); }); it('should append node to linked list', () => { const linkedList = new LinkedList(); expect(linkedList.head).toBeNull(); expect(linkedList.tail).toBeNull(); linkedList.append(1); linkedList.append(2); expect(linkedList.toString()).toBe('1,2'); expect(linkedList.tail.next).toBeNull(); }); it('should prepend node to linked list', () => { const linkedList = new LinkedList(); linkedList.prepend(2); expect(linkedList.head.toString()).toBe('2'); expect(linkedList.tail.toString()).toBe('2'); linkedList.append(1); linkedList.prepend(3); expect(linkedList.toString()).toBe('3,2,1'); }); it('should insert node to linked list', () => { const linkedList = new LinkedList(); linkedList.insert(4, 3); expect(linkedList.head.toString()).toBe('4'); expect(linkedList.tail.toString()).toBe('4'); linkedList.insert(3, 2); linkedList.insert(2, 1); linkedList.insert(1, -7); linkedList.insert(10, 9); expect(linkedList.toString()).toBe('1,4,2,3,10'); }); it('should delete node by value from linked list', () => { const linkedList = new LinkedList(); expect(linkedList.delete(5)).toBeNull(); linkedList.append(1); linkedList.append(1); linkedList.append(2); linkedList.append(3); linkedList.append(3); linkedList.append(3); linkedList.append(4); linkedList.append(5); expect(linkedList.head.toString()).toBe('1'); expect(linkedList.tail.toString()).toBe('5'); const deletedNode = linkedList.delete(3); expect(deletedNode.value).toBe(3); expect(linkedList.toString()).toBe('1,1,2,4,5'); linkedList.delete(3); expect(linkedList.toString()).toBe('1,1,2,4,5'); linkedList.delete(1); expect(linkedList.toString()).toBe('2,4,5'); expect(linkedList.head.toString()).toBe('2'); expect(linkedList.tail.toString()).toBe('5'); linkedList.delete(5); expect(linkedList.toString()).toBe('2,4'); expect(linkedList.head.toString()).toBe('2'); expect(linkedList.tail.toString()).toBe('4'); linkedList.delete(4); expect(linkedList.toString()).toBe('2'); expect(linkedList.head.toString()).toBe('2'); expect(linkedList.tail.toString()).toBe('2'); linkedList.delete(2); expect(linkedList.toString()).toBe(''); }); it('should delete linked list tail', () => { const linkedList = new LinkedList(); linkedList.append(1); linkedList.append(2); linkedList.append(3); expect(linkedList.head.toString()).toBe('1'); expect(linkedList.tail.toString()).toBe('3'); const deletedNode1 = linkedList.deleteTail(); expect(deletedNode1.value).toBe(3); expect(linkedList.toString()).toBe('1,2'); expect(linkedList.head.toString()).toBe('1'); expect(linkedList.tail.toString()).toBe('2'); const deletedNode2 = linkedList.deleteTail(); expect(deletedNode2.value).toBe(2); expect(linkedList.toString()).toBe('1'); expect(linkedList.head.toString()).toBe('1'); expect(linkedList.tail.toString()).toBe('1'); const deletedNode3 = linkedList.deleteTail(); expect(deletedNode3.value).toBe(1); expect(linkedList.toString()).toBe(''); expect(linkedList.head).toBeNull(); expect(linkedList.tail).toBeNull(); }); it('should delete linked list head', () => { const linkedList = new LinkedList(); expect(linkedList.deleteHead()).toBeNull(); linkedList.append(1); linkedList.append(2); expect(linkedList.head.toString()).toBe('1'); expect(linkedList.tail.toString()).toBe('2'); const deletedNode1 = linkedList.deleteHead(); expect(deletedNode1.value).toBe(1); expect(linkedList.toString()).toBe('2'); expect(linkedList.head.toString()).toBe('2'); expect(linkedList.tail.toString()).toBe('2'); const deletedNode2 = linkedList.deleteHead(); expect(deletedNode2.value).toBe(2); expect(linkedList.toString()).toBe(''); expect(linkedList.head).toBeNull(); expect(linkedList.tail).toBeNull(); }); it('should be possible to store objects in the list and to print them out', () => { const linkedList = new LinkedList(); const nodeValue1 = { value: 1, key: 'key1' }; const nodeValue2 = { value: 2, key: 'key2' }; linkedList .append(nodeValue1) .prepend(nodeValue2); const nodeStringifier = (value) => `${value.key}:${value.value}`; expect(linkedList.toString(nodeStringifier)).toBe('key2:2,key1:1'); }); it('should find node by value', () => { const linkedList = new LinkedList(); expect(linkedList.find({ value: 5 })).toBeNull(); linkedList.append(1); expect(linkedList.find({ value: 1 })).toBeDefined(); linkedList .append(2) .append(3); const node = linkedList.find({ value: 2 }); expect(node.value).toBe(2); expect(linkedList.find({ value: 5 })).toBeNull(); }); it('should find node by callback', () => { const linkedList = new LinkedList(); linkedList .append({ value: 1, key: 'test1' }) .append({ value: 2, key: 'test2' }) .append({ value: 3, key: 'test3' }); const node = linkedList.find({ callback: (value) => value.key === 'test2' }); expect(node).toBeDefined(); expect(node.value.value).toBe(2); expect(node.value.key).toBe('test2'); expect(linkedList.find({ callback: (value) => value.key === 'test5' })).toBeNull(); }); it('should create linked list from array', () => { const linkedList = new LinkedList(); linkedList.fromArray([1, 1, 2, 3, 3, 3, 4, 5]); expect(linkedList.toString()).toBe('1,1,2,3,3,3,4,5'); }); it('should find node by means of custom compare function', () => { const comparatorFunction = (a, b) => { if (a.customValue === b.customValue) { return 0; } return a.customValue < b.customValue ? -1 : 1; }; const linkedList = new LinkedList(comparatorFunction); linkedList .append({ value: 1, customValue: 'test1' }) .append({ value: 2, customValue: 'test2' }) .append({ value: 3, customValue: 'test3' }); const node = linkedList.find({ value: { value: 2, customValue: 'test2' }, }); expect(node).toBeDefined(); expect(node.value.value).toBe(2); expect(node.value.customValue).toBe('test2'); expect(linkedList.find({ value: { value: 2, customValue: 'test5' } })).toBeNull(); }); it('should find preferring callback over compare function', () => { const greaterThan = (value, compareTo) => (value > compareTo ? 0 : 1); const linkedList = new LinkedList(greaterThan); linkedList.fromArray([1, 2, 3, 4, 5]); let node = linkedList.find({ value: 3 }); expect(node.value).toBe(4); node = linkedList.find({ callback: (value) => value < 3 }); expect(node.value).toBe(1); }); it('should convert to array', () => { const linkedList = new LinkedList(); linkedList.append(1); linkedList.append(2); linkedList.append(3); expect(linkedList.toArray().join(',')).toBe('1,2,3'); }); it('should reverse linked list', () => { const linkedList = new LinkedList(); // Add test values to linked list. linkedList .append(1) .append(2) .append(3); expect(linkedList.toString()).toBe('1,2,3'); expect(linkedList.head.value).toBe(1); expect(linkedList.tail.value).toBe(3); // Reverse linked list. linkedList.reverse(); expect(linkedList.toString()).toBe('3,2,1'); expect(linkedList.head.value).toBe(3); expect(linkedList.tail.value).toBe(1); // Reverse linked list back to initial state. linkedList.reverse(); expect(linkedList.toString()).toBe('1,2,3'); expect(linkedList.head.value).toBe(1); expect(linkedList.tail.value).toBe(3); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/lru-cache/LRUCache.js
src/data-structures/lru-cache/LRUCache.js
/* eslint-disable no-param-reassign, max-classes-per-file */ /** * Simple implementation of the Doubly-Linked List Node * that is used in LRUCache class below. */ class LinkedListNode { /** * Creates a doubly-linked list node. * @param {string} key * @param {any} val * @param {LinkedListNode} prev * @param {LinkedListNode} next */ constructor(key, val, prev = null, next = null) { this.key = key; this.val = val; this.prev = prev; this.next = next; } } /** * Implementation of the LRU (Least Recently Used) Cache * based on the HashMap and Doubly Linked List data-structures. * * Current implementation allows to have fast O(1) (in average) read and write operations. * * At any moment in time the LRU Cache holds not more that "capacity" number of items in it. */ class LRUCache { /** * Creates a cache instance of a specific capacity. * @param {number} capacity */ constructor(capacity) { this.capacity = capacity; // How many items to store in cache at max. this.nodesMap = {}; // The quick links to each linked list node in cache. this.size = 0; // The number of items that is currently stored in the cache. this.head = new LinkedListNode(); // The Head (first) linked list node. this.tail = new LinkedListNode(); // The Tail (last) linked list node. } /** * Returns the cached value by its key. * Time complexity: O(1) in average. * @param {string} key * @returns {any} */ get(key) { if (this.nodesMap[key] === undefined) return undefined; const node = this.nodesMap[key]; this.promote(node); return node.val; } /** * Sets the value to cache by its key. * Time complexity: O(1) in average. * @param {string} key * @param {any} val */ set(key, val) { if (this.nodesMap[key]) { const node = this.nodesMap[key]; node.val = val; this.promote(node); } else { const node = new LinkedListNode(key, val); this.append(node); } } /** * Promotes the node to the end of the linked list. * It means that the node is most frequently used. * It also reduces the chance for such node to get evicted from cache. * @param {LinkedListNode} node */ promote(node) { this.evict(node); this.append(node); } /** * Appends a new node to the end of the cache linked list. * @param {LinkedListNode} node */ append(node) { this.nodesMap[node.key] = node; if (!this.head.next) { // First node to append. this.head.next = node; this.tail.prev = node; node.prev = this.head; node.next = this.tail; } else { // Append to an existing tail. const oldTail = this.tail.prev; oldTail.next = node; node.prev = oldTail; node.next = this.tail; this.tail.prev = node; } this.size += 1; if (this.size > this.capacity) { this.evict(this.head.next); } } /** * Evicts (removes) the node from cache linked list. * @param {LinkedListNode} node */ evict(node) { delete this.nodesMap[node.key]; this.size -= 1; const prevNode = node.prev; const nextNode = node.next; // If one and only node. if (prevNode === this.head && nextNode === this.tail) { this.head.next = null; this.tail.prev = null; this.size = 0; return; } // If this is a Head node. if (prevNode === this.head) { nextNode.prev = this.head; this.head.next = nextNode; return; } // If this is a Tail node. if (nextNode === this.tail) { prevNode.next = this.tail; this.tail.prev = prevNode; return; } // If the node is in the middle. prevNode.next = nextNode; nextNode.prev = prevNode; } } export default LRUCache;
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/lru-cache/LRUCacheOnMap.js
src/data-structures/lru-cache/LRUCacheOnMap.js
/* eslint-disable no-restricted-syntax, no-unreachable-loop */ /** * Implementation of the LRU (Least Recently Used) Cache * based on the (ordered) Map data-structure. * * Current implementation allows to have fast O(1) (in average) read and write operations. * * At any moment in time the LRU Cache holds not more that "capacity" number of items in it. */ class LRUCacheOnMap { /** * Creates a cache instance of a specific capacity. * @param {number} capacity */ constructor(capacity) { this.capacity = capacity; // How many items to store in cache at max. this.items = new Map(); // The ordered hash map of all cached items. } /** * Returns the cached value by its key. * Time complexity: O(1) in average. * @param {string} key * @returns {any} */ get(key) { if (!this.items.has(key)) return undefined; const val = this.items.get(key); this.items.delete(key); this.items.set(key, val); return val; } /** * Sets the value to cache by its key. * Time complexity: O(1). * @param {string} key * @param {any} val */ set(key, val) { this.items.delete(key); this.items.set(key, val); if (this.items.size > this.capacity) { for (const headKey of this.items.keys()) { this.items.delete(headKey); break; } } } } export default LRUCacheOnMap;
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/lru-cache/__test__/LRUCache.test.js
src/data-structures/lru-cache/__test__/LRUCache.test.js
import LRUCache from '../LRUCache'; describe('LRUCache', () => { it('should set and get values to and from the cache', () => { const cache = new LRUCache(100); expect(cache.get('key-1')).toBeUndefined(); cache.set('key-1', 15); cache.set('key-2', 16); cache.set('key-3', 17); expect(cache.get('key-1')).toBe(15); expect(cache.get('key-2')).toBe(16); expect(cache.get('key-3')).toBe(17); expect(cache.get('key-3')).toBe(17); expect(cache.get('key-2')).toBe(16); expect(cache.get('key-1')).toBe(15); cache.set('key-1', 5); cache.set('key-2', 6); cache.set('key-3', 7); expect(cache.get('key-1')).toBe(5); expect(cache.get('key-2')).toBe(6); expect(cache.get('key-3')).toBe(7); }); it('should evict least recently used items from cache with cache size of 1', () => { const cache = new LRUCache(1); expect(cache.get('key-1')).toBeUndefined(); cache.set('key-1', 15); expect(cache.get('key-1')).toBe(15); cache.set('key-2', 16); expect(cache.get('key-1')).toBeUndefined(); expect(cache.get('key-2')).toBe(16); cache.set('key-2', 17); expect(cache.get('key-2')).toBe(17); cache.set('key-3', 18); cache.set('key-4', 19); expect(cache.get('key-2')).toBeUndefined(); expect(cache.get('key-3')).toBeUndefined(); expect(cache.get('key-4')).toBe(19); }); it('should evict least recently used items from cache with cache size of 2', () => { const cache = new LRUCache(2); expect(cache.get('key-21')).toBeUndefined(); cache.set('key-21', 15); expect(cache.get('key-21')).toBe(15); cache.set('key-22', 16); expect(cache.get('key-21')).toBe(15); expect(cache.get('key-22')).toBe(16); cache.set('key-22', 17); expect(cache.get('key-22')).toBe(17); cache.set('key-23', 18); expect(cache.size).toBe(2); expect(cache.get('key-21')).toBeUndefined(); expect(cache.get('key-22')).toBe(17); expect(cache.get('key-23')).toBe(18); cache.set('key-24', 19); expect(cache.size).toBe(2); expect(cache.get('key-21')).toBeUndefined(); expect(cache.get('key-22')).toBeUndefined(); expect(cache.get('key-23')).toBe(18); expect(cache.get('key-24')).toBe(19); }); it('should evict least recently used items from cache with cache size of 3', () => { const cache = new LRUCache(3); cache.set('key-1', 1); cache.set('key-2', 2); cache.set('key-3', 3); expect(cache.get('key-1')).toBe(1); expect(cache.get('key-2')).toBe(2); expect(cache.get('key-3')).toBe(3); cache.set('key-3', 4); expect(cache.get('key-1')).toBe(1); expect(cache.get('key-2')).toBe(2); expect(cache.get('key-3')).toBe(4); cache.set('key-4', 5); expect(cache.get('key-1')).toBeUndefined(); expect(cache.get('key-2')).toBe(2); expect(cache.get('key-3')).toBe(4); expect(cache.get('key-4')).toBe(5); }); it('should promote the node while calling set() method', () => { const cache = new LRUCache(2); cache.set('2', 1); cache.set('1', 1); cache.set('2', 3); cache.set('4', 1); expect(cache.get('1')).toBeUndefined(); expect(cache.get('2')).toBe(3); }); it('should promote the recently accessed item with cache size of 3', () => { const cache = new LRUCache(3); cache.set('key-1', 1); cache.set('key-2', 2); cache.set('key-3', 3); expect(cache.get('key-1')).toBe(1); cache.set('key-4', 4); expect(cache.get('key-1')).toBe(1); expect(cache.get('key-3')).toBe(3); expect(cache.get('key-4')).toBe(4); expect(cache.get('key-2')).toBeUndefined(); }); it('should promote the recently accessed item with cache size of 4', () => { const cache = new LRUCache(4); cache.set('key-1', 1); cache.set('key-2', 2); cache.set('key-3', 3); cache.set('key-4', 4); expect(cache.get('key-4')).toBe(4); expect(cache.get('key-3')).toBe(3); expect(cache.get('key-2')).toBe(2); expect(cache.get('key-1')).toBe(1); cache.set('key-5', 5); expect(cache.get('key-1')).toBe(1); expect(cache.get('key-2')).toBe(2); expect(cache.get('key-3')).toBe(3); expect(cache.get('key-4')).toBeUndefined(); expect(cache.get('key-5')).toBe(5); cache.set('key-6', 6); expect(cache.get('key-1')).toBeUndefined(); expect(cache.get('key-2')).toBe(2); expect(cache.get('key-3')).toBe(3); expect(cache.get('key-4')).toBeUndefined(); expect(cache.get('key-5')).toBe(5); expect(cache.get('key-6')).toBe(6); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/lru-cache/__test__/LRUCacheOnMap.test.js
src/data-structures/lru-cache/__test__/LRUCacheOnMap.test.js
import LRUCache from '../LRUCacheOnMap'; describe('LRUCacheOnMap', () => { it('should set and get values to and from the cache', () => { const cache = new LRUCache(100); expect(cache.get('key-1')).toBeUndefined(); cache.set('key-1', 15); cache.set('key-2', 16); cache.set('key-3', 17); expect(cache.get('key-1')).toBe(15); expect(cache.get('key-2')).toBe(16); expect(cache.get('key-3')).toBe(17); expect(cache.get('key-3')).toBe(17); expect(cache.get('key-2')).toBe(16); expect(cache.get('key-1')).toBe(15); cache.set('key-1', 5); cache.set('key-2', 6); cache.set('key-3', 7); expect(cache.get('key-1')).toBe(5); expect(cache.get('key-2')).toBe(6); expect(cache.get('key-3')).toBe(7); }); it('should evict least recently used items from cache with cache size of 1', () => { const cache = new LRUCache(1); expect(cache.get('key-1')).toBeUndefined(); cache.set('key-1', 15); expect(cache.get('key-1')).toBe(15); cache.set('key-2', 16); expect(cache.get('key-1')).toBeUndefined(); expect(cache.get('key-2')).toBe(16); cache.set('key-2', 17); expect(cache.get('key-2')).toBe(17); cache.set('key-3', 18); cache.set('key-4', 19); expect(cache.get('key-2')).toBeUndefined(); expect(cache.get('key-3')).toBeUndefined(); expect(cache.get('key-4')).toBe(19); }); it('should evict least recently used items from cache with cache size of 2', () => { const cache = new LRUCache(2); expect(cache.get('key-21')).toBeUndefined(); cache.set('key-21', 15); expect(cache.get('key-21')).toBe(15); cache.set('key-22', 16); expect(cache.get('key-21')).toBe(15); expect(cache.get('key-22')).toBe(16); cache.set('key-22', 17); expect(cache.get('key-22')).toBe(17); cache.set('key-23', 18); expect(cache.get('key-21')).toBeUndefined(); expect(cache.get('key-22')).toBe(17); expect(cache.get('key-23')).toBe(18); cache.set('key-24', 19); expect(cache.get('key-21')).toBeUndefined(); expect(cache.get('key-22')).toBeUndefined(); expect(cache.get('key-23')).toBe(18); expect(cache.get('key-24')).toBe(19); }); it('should evict least recently used items from cache with cache size of 3', () => { const cache = new LRUCache(3); cache.set('key-1', 1); cache.set('key-2', 2); cache.set('key-3', 3); expect(cache.get('key-1')).toBe(1); expect(cache.get('key-2')).toBe(2); expect(cache.get('key-3')).toBe(3); cache.set('key-3', 4); expect(cache.get('key-1')).toBe(1); expect(cache.get('key-2')).toBe(2); expect(cache.get('key-3')).toBe(4); cache.set('key-4', 5); expect(cache.get('key-1')).toBeUndefined(); expect(cache.get('key-2')).toBe(2); expect(cache.get('key-3')).toBe(4); expect(cache.get('key-4')).toBe(5); }); it('should promote the node while calling set() method', () => { const cache = new LRUCache(2); cache.set('2', 1); cache.set('1', 1); cache.set('2', 3); cache.set('4', 1); expect(cache.get('1')).toBeUndefined(); expect(cache.get('2')).toBe(3); }); it('should promote the recently accessed item with cache size of 3', () => { const cache = new LRUCache(3); cache.set('key-1', 1); cache.set('key-2', 2); cache.set('key-3', 3); expect(cache.get('key-1')).toBe(1); cache.set('key-4', 4); expect(cache.get('key-1')).toBe(1); expect(cache.get('key-3')).toBe(3); expect(cache.get('key-4')).toBe(4); expect(cache.get('key-2')).toBeUndefined(); }); it('should promote the recently accessed item with cache size of 4', () => { const cache = new LRUCache(4); cache.set('key-1', 1); cache.set('key-2', 2); cache.set('key-3', 3); cache.set('key-4', 4); expect(cache.get('key-4')).toBe(4); expect(cache.get('key-3')).toBe(3); expect(cache.get('key-2')).toBe(2); expect(cache.get('key-1')).toBe(1); cache.set('key-5', 5); expect(cache.get('key-1')).toBe(1); expect(cache.get('key-2')).toBe(2); expect(cache.get('key-3')).toBe(3); expect(cache.get('key-4')).toBeUndefined(); expect(cache.get('key-5')).toBe(5); cache.set('key-6', 6); expect(cache.get('key-1')).toBeUndefined(); expect(cache.get('key-2')).toBe(2); expect(cache.get('key-3')).toBe(3); expect(cache.get('key-4')).toBeUndefined(); expect(cache.get('key-5')).toBe(5); expect(cache.get('key-6')).toBe(6); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/stack/Stack.js
src/data-structures/stack/Stack.js
import LinkedList from '../linked-list/LinkedList'; export default class Stack { constructor() { // We're going to implement Stack based on LinkedList since these // structures are quite similar. Compare push/pop operations of the Stack // with prepend/deleteHead operations of LinkedList. this.linkedList = new LinkedList(); } /** * @return {boolean} */ isEmpty() { // The stack is empty if its linked list doesn't have a head. return !this.linkedList.head; } /** * @return {*} */ peek() { if (this.isEmpty()) { // If the linked list is empty then there is nothing to peek from. return null; } // Just read the value from the start of linked list without deleting it. return this.linkedList.head.value; } /** * @param {*} value */ push(value) { // Pushing means to lay the value on top of the stack. Therefore let's just add // the new value at the start of the linked list. this.linkedList.prepend(value); } /** * @return {*} */ pop() { // Let's try to delete the first node (the head) from the linked list. // If there is no head (the linked list is empty) just return null. const removedHead = this.linkedList.deleteHead(); return removedHead ? removedHead.value : null; } /** * @return {*[]} */ toArray() { return this.linkedList .toArray() .map((linkedListNode) => linkedListNode.value); } /** * @param {function} [callback] * @return {string} */ toString(callback) { return this.linkedList.toString(callback); } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/stack/__test__/Stack.test.js
src/data-structures/stack/__test__/Stack.test.js
import Stack from '../Stack'; describe('Stack', () => { it('should create empty stack', () => { const stack = new Stack(); expect(stack).not.toBeNull(); expect(stack.linkedList).not.toBeNull(); }); it('should stack data to stack', () => { const stack = new Stack(); stack.push(1); stack.push(2); expect(stack.toString()).toBe('2,1'); }); it('should peek data from stack', () => { const stack = new Stack(); expect(stack.peek()).toBeNull(); stack.push(1); stack.push(2); expect(stack.peek()).toBe(2); expect(stack.peek()).toBe(2); }); it('should check if stack is empty', () => { const stack = new Stack(); expect(stack.isEmpty()).toBe(true); stack.push(1); expect(stack.isEmpty()).toBe(false); }); it('should pop data from stack', () => { const stack = new Stack(); stack.push(1); stack.push(2); expect(stack.pop()).toBe(2); expect(stack.pop()).toBe(1); expect(stack.pop()).toBeNull(); expect(stack.isEmpty()).toBe(true); }); it('should be possible to push/pop objects', () => { const stack = new Stack(); stack.push({ value: 'test1', key: 'key1' }); stack.push({ value: 'test2', key: 'key2' }); const stringifier = (value) => `${value.key}:${value.value}`; expect(stack.toString(stringifier)).toBe('key2:test2,key1:test1'); expect(stack.pop().value).toBe('test2'); expect(stack.pop().value).toBe('test1'); }); it('should be possible to convert stack to array', () => { const stack = new Stack(); expect(stack.peek()).toBeNull(); stack.push(1); stack.push(2); stack.push(3); expect(stack.toArray()).toEqual([3, 2, 1]); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/queue/Queue.js
src/data-structures/queue/Queue.js
import LinkedList from '../linked-list/LinkedList'; export default class Queue { constructor() { // We're going to implement Queue based on LinkedList since the two // structures are quite similar. Namely, they both operate mostly on // the elements at the beginning and the end. Compare enqueue/dequeue // operations of Queue with append/deleteHead operations of LinkedList. this.linkedList = new LinkedList(); } /** * @return {boolean} */ isEmpty() { return !this.linkedList.head; } /** * Read the element at the front of the queue without removing it. * @return {*} */ peek() { if (this.isEmpty()) { return null; } return this.linkedList.head.value; } /** * Add a new element to the end of the queue (the tail of the linked list). * This element will be processed after all elements ahead of it. * @param {*} value */ enqueue(value) { this.linkedList.append(value); } /** * Remove the element at the front of the queue (the head of the linked list). * If the queue is empty, return null. * @return {*} */ dequeue() { const removedHead = this.linkedList.deleteHead(); return removedHead ? removedHead.value : null; } /** * @param [callback] * @return {string} */ toString(callback) { // Return string representation of the queue's linked list. return this.linkedList.toString(callback); } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/queue/__test__/Queue.test.js
src/data-structures/queue/__test__/Queue.test.js
import Queue from '../Queue'; describe('Queue', () => { it('should create empty queue', () => { const queue = new Queue(); expect(queue).not.toBeNull(); expect(queue.linkedList).not.toBeNull(); }); it('should enqueue data to queue', () => { const queue = new Queue(); queue.enqueue(1); queue.enqueue(2); expect(queue.toString()).toBe('1,2'); }); it('should be possible to enqueue/dequeue objects', () => { const queue = new Queue(); queue.enqueue({ value: 'test1', key: 'key1' }); queue.enqueue({ value: 'test2', key: 'key2' }); const stringifier = (value) => `${value.key}:${value.value}`; expect(queue.toString(stringifier)).toBe('key1:test1,key2:test2'); expect(queue.dequeue().value).toBe('test1'); expect(queue.dequeue().value).toBe('test2'); }); it('should peek data from queue', () => { const queue = new Queue(); expect(queue.peek()).toBeNull(); queue.enqueue(1); queue.enqueue(2); expect(queue.peek()).toBe(1); expect(queue.peek()).toBe(1); }); it('should check if queue is empty', () => { const queue = new Queue(); expect(queue.isEmpty()).toBe(true); queue.enqueue(1); expect(queue.isEmpty()).toBe(false); }); it('should dequeue from queue in FIFO order', () => { const queue = new Queue(); queue.enqueue(1); queue.enqueue(2); expect(queue.dequeue()).toBe(1); expect(queue.dequeue()).toBe(2); expect(queue.dequeue()).toBeNull(); expect(queue.isEmpty()).toBe(true); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/doubly-linked-list/DoublyLinkedList.js
src/data-structures/doubly-linked-list/DoublyLinkedList.js
import DoublyLinkedListNode from './DoublyLinkedListNode'; import Comparator from '../../utils/comparator/Comparator'; export default class DoublyLinkedList { /** * @param {Function} [comparatorFunction] */ constructor(comparatorFunction) { /** @var DoublyLinkedListNode */ this.head = null; /** @var DoublyLinkedListNode */ this.tail = null; this.compare = new Comparator(comparatorFunction); } /** * @param {*} value * @return {DoublyLinkedList} */ prepend(value) { // Make new node to be a head. const newNode = new DoublyLinkedListNode(value, this.head); // If there is head, then it won't be head anymore. // Therefore, make its previous reference to be new node (new head). // Then mark the new node as head. if (this.head) { this.head.previous = newNode; } this.head = newNode; // If there is no tail yet let's make new node a tail. if (!this.tail) { this.tail = newNode; } return this; } /** * @param {*} value * @return {DoublyLinkedList} */ append(value) { const newNode = new DoublyLinkedListNode(value); // If there is no head yet let's make new node a head. if (!this.head) { this.head = newNode; this.tail = newNode; return this; } // Attach new node to the end of linked list. this.tail.next = newNode; // Attach current tail to the new node's previous reference. newNode.previous = this.tail; // Set new node to be the tail of linked list. this.tail = newNode; return this; } /** * @param {*} value * @return {DoublyLinkedListNode} */ delete(value) { if (!this.head) { return null; } let deletedNode = null; let currentNode = this.head; while (currentNode) { if (this.compare.equal(currentNode.value, value)) { deletedNode = currentNode; if (deletedNode === this.head) { // If HEAD is going to be deleted... // Set head to second node, which will become new head. this.head = deletedNode.next; // Set new head's previous to null. if (this.head) { this.head.previous = null; } // If all the nodes in list has same value that is passed as argument // then all nodes will get deleted, therefore tail needs to be updated. if (deletedNode === this.tail) { this.tail = null; } } else if (deletedNode === this.tail) { // If TAIL is going to be deleted... // Set tail to second last node, which will become new tail. this.tail = deletedNode.previous; this.tail.next = null; } else { // If MIDDLE node is going to be deleted... const previousNode = deletedNode.previous; const nextNode = deletedNode.next; previousNode.next = nextNode; nextNode.previous = previousNode; } } currentNode = currentNode.next; } return deletedNode; } /** * @param {Object} findParams * @param {*} findParams.value * @param {function} [findParams.callback] * @return {DoublyLinkedListNode} */ find({ value = undefined, callback = undefined }) { if (!this.head) { return null; } let currentNode = this.head; while (currentNode) { // If callback is specified then try to find node by callback. if (callback && callback(currentNode.value)) { return currentNode; } // If value is specified then try to compare by value.. if (value !== undefined && this.compare.equal(currentNode.value, value)) { return currentNode; } currentNode = currentNode.next; } return null; } /** * @return {DoublyLinkedListNode} */ deleteTail() { if (!this.tail) { // No tail to delete. return null; } if (this.head === this.tail) { // There is only one node in linked list. const deletedTail = this.tail; this.head = null; this.tail = null; return deletedTail; } // If there are many nodes in linked list... const deletedTail = this.tail; this.tail = this.tail.previous; this.tail.next = null; return deletedTail; } /** * @return {DoublyLinkedListNode} */ deleteHead() { if (!this.head) { return null; } const deletedHead = this.head; if (this.head.next) { this.head = this.head.next; this.head.previous = null; } else { this.head = null; this.tail = null; } return deletedHead; } /** * @return {DoublyLinkedListNode[]} */ toArray() { const nodes = []; let currentNode = this.head; while (currentNode) { nodes.push(currentNode); currentNode = currentNode.next; } return nodes; } /** * @param {*[]} values - Array of values that need to be converted to linked list. * @return {DoublyLinkedList} */ fromArray(values) { values.forEach((value) => this.append(value)); return this; } /** * @param {function} [callback] * @return {string} */ toString(callback) { return this.toArray().map((node) => node.toString(callback)).toString(); } /** * Reverse a linked list. * @returns {DoublyLinkedList} */ reverse() { let currNode = this.head; let prevNode = null; let nextNode = null; while (currNode) { // Store next node. nextNode = currNode.next; prevNode = currNode.previous; // Change next node of the current node so it would link to previous node. currNode.next = prevNode; currNode.previous = nextNode; // Move prevNode and currNode nodes one step forward. prevNode = currNode; currNode = nextNode; } // Reset head and tail. this.tail = this.head; this.head = prevNode; return this; } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/doubly-linked-list/DoublyLinkedListNode.js
src/data-structures/doubly-linked-list/DoublyLinkedListNode.js
export default class DoublyLinkedListNode { constructor(value, next = null, previous = null) { this.value = value; this.next = next; this.previous = previous; } toString(callback) { return callback ? callback(this.value) : `${this.value}`; } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/doubly-linked-list/__test__/DoublyLinkedList.test.js
src/data-structures/doubly-linked-list/__test__/DoublyLinkedList.test.js
import DoublyLinkedList from '../DoublyLinkedList'; describe('DoublyLinkedList', () => { it('should create empty linked list', () => { const linkedList = new DoublyLinkedList(); expect(linkedList.toString()).toBe(''); }); it('should append node to linked list', () => { const linkedList = new DoublyLinkedList(); expect(linkedList.head).toBeNull(); expect(linkedList.tail).toBeNull(); linkedList.append(1); linkedList.append(2); expect(linkedList.head.next.value).toBe(2); expect(linkedList.tail.previous.value).toBe(1); expect(linkedList.toString()).toBe('1,2'); }); it('should prepend node to linked list', () => { const linkedList = new DoublyLinkedList(); linkedList.prepend(2); expect(linkedList.head.toString()).toBe('2'); expect(linkedList.tail.toString()).toBe('2'); linkedList.append(1); linkedList.prepend(3); expect(linkedList.head.next.next.previous).toBe(linkedList.head.next); expect(linkedList.tail.previous.next).toBe(linkedList.tail); expect(linkedList.tail.previous.value).toBe(2); expect(linkedList.toString()).toBe('3,2,1'); }); it('should create linked list from array', () => { const linkedList = new DoublyLinkedList(); linkedList.fromArray([1, 1, 2, 3, 3, 3, 4, 5]); expect(linkedList.toString()).toBe('1,1,2,3,3,3,4,5'); }); it('should delete node by value from linked list', () => { const linkedList = new DoublyLinkedList(); expect(linkedList.delete(5)).toBeNull(); linkedList.append(1); linkedList.append(1); linkedList.append(2); linkedList.append(3); linkedList.append(3); linkedList.append(3); linkedList.append(4); linkedList.append(5); expect(linkedList.head.toString()).toBe('1'); expect(linkedList.tail.toString()).toBe('5'); const deletedNode = linkedList.delete(3); expect(deletedNode.value).toBe(3); expect(linkedList.tail.previous.previous.value).toBe(2); expect(linkedList.toString()).toBe('1,1,2,4,5'); linkedList.delete(3); expect(linkedList.toString()).toBe('1,1,2,4,5'); linkedList.delete(1); expect(linkedList.toString()).toBe('2,4,5'); expect(linkedList.head.toString()).toBe('2'); expect(linkedList.head.next.next).toBe(linkedList.tail); expect(linkedList.tail.previous.previous).toBe(linkedList.head); expect(linkedList.tail.toString()).toBe('5'); linkedList.delete(5); expect(linkedList.toString()).toBe('2,4'); expect(linkedList.head.toString()).toBe('2'); expect(linkedList.tail.toString()).toBe('4'); linkedList.delete(4); expect(linkedList.toString()).toBe('2'); expect(linkedList.head.toString()).toBe('2'); expect(linkedList.tail.toString()).toBe('2'); expect(linkedList.head).toBe(linkedList.tail); linkedList.delete(2); expect(linkedList.toString()).toBe(''); }); it('should delete linked list tail', () => { const linkedList = new DoublyLinkedList(); expect(linkedList.deleteTail()).toBeNull(); linkedList.append(1); linkedList.append(2); linkedList.append(3); expect(linkedList.head.toString()).toBe('1'); expect(linkedList.tail.toString()).toBe('3'); const deletedNode1 = linkedList.deleteTail(); expect(deletedNode1.value).toBe(3); expect(linkedList.toString()).toBe('1,2'); expect(linkedList.head.toString()).toBe('1'); expect(linkedList.tail.toString()).toBe('2'); const deletedNode2 = linkedList.deleteTail(); expect(deletedNode2.value).toBe(2); expect(linkedList.toString()).toBe('1'); expect(linkedList.head.toString()).toBe('1'); expect(linkedList.tail.toString()).toBe('1'); const deletedNode3 = linkedList.deleteTail(); expect(deletedNode3.value).toBe(1); expect(linkedList.toString()).toBe(''); expect(linkedList.head).toBeNull(); expect(linkedList.tail).toBeNull(); }); it('should delete linked list head', () => { const linkedList = new DoublyLinkedList(); expect(linkedList.deleteHead()).toBeNull(); linkedList.append(1); linkedList.append(2); expect(linkedList.head.toString()).toBe('1'); expect(linkedList.tail.toString()).toBe('2'); const deletedNode1 = linkedList.deleteHead(); expect(deletedNode1.value).toBe(1); expect(linkedList.head.previous).toBeNull(); expect(linkedList.toString()).toBe('2'); expect(linkedList.head.toString()).toBe('2'); expect(linkedList.tail.toString()).toBe('2'); const deletedNode2 = linkedList.deleteHead(); expect(deletedNode2.value).toBe(2); expect(linkedList.toString()).toBe(''); expect(linkedList.head).toBeNull(); expect(linkedList.tail).toBeNull(); }); it('should be possible to store objects in the list and to print them out', () => { const linkedList = new DoublyLinkedList(); const nodeValue1 = { value: 1, key: 'key1' }; const nodeValue2 = { value: 2, key: 'key2' }; linkedList .append(nodeValue1) .prepend(nodeValue2); const nodeStringifier = (value) => `${value.key}:${value.value}`; expect(linkedList.toString(nodeStringifier)).toBe('key2:2,key1:1'); }); it('should find node by value', () => { const linkedList = new DoublyLinkedList(); expect(linkedList.find({ value: 5 })).toBeNull(); linkedList.append(1); expect(linkedList.find({ value: 1 })).toBeDefined(); linkedList .append(2) .append(3); const node = linkedList.find({ value: 2 }); expect(node.value).toBe(2); expect(linkedList.find({ value: 5 })).toBeNull(); }); it('should find node by callback', () => { const linkedList = new DoublyLinkedList(); linkedList .append({ value: 1, key: 'test1' }) .append({ value: 2, key: 'test2' }) .append({ value: 3, key: 'test3' }); const node = linkedList.find({ callback: (value) => value.key === 'test2' }); expect(node).toBeDefined(); expect(node.value.value).toBe(2); expect(node.value.key).toBe('test2'); expect(linkedList.find({ callback: (value) => value.key === 'test5' })).toBeNull(); }); it('should find node by means of custom compare function', () => { const comparatorFunction = (a, b) => { if (a.customValue === b.customValue) { return 0; } return a.customValue < b.customValue ? -1 : 1; }; const linkedList = new DoublyLinkedList(comparatorFunction); linkedList .append({ value: 1, customValue: 'test1' }) .append({ value: 2, customValue: 'test2' }) .append({ value: 3, customValue: 'test3' }); const node = linkedList.find({ value: { value: 2, customValue: 'test2' }, }); expect(node).toBeDefined(); expect(node.value.value).toBe(2); expect(node.value.customValue).toBe('test2'); expect(linkedList.find({ value: 2, customValue: 'test5' })).toBeNull(); }); it('should reverse linked list', () => { const linkedList = new DoublyLinkedList(); // Add test values to linked list. linkedList .append(1) .append(2) .append(3) .append(4); expect(linkedList.toString()).toBe('1,2,3,4'); expect(linkedList.head.value).toBe(1); expect(linkedList.tail.value).toBe(4); // Reverse linked list. linkedList.reverse(); expect(linkedList.toString()).toBe('4,3,2,1'); expect(linkedList.head.previous).toBeNull(); expect(linkedList.head.value).toBe(4); expect(linkedList.head.next.value).toBe(3); expect(linkedList.head.next.next.value).toBe(2); expect(linkedList.head.next.next.next.value).toBe(1); expect(linkedList.tail.next).toBeNull(); expect(linkedList.tail.value).toBe(1); expect(linkedList.tail.previous.value).toBe(2); expect(linkedList.tail.previous.previous.value).toBe(3); expect(linkedList.tail.previous.previous.previous.value).toBe(4); // Reverse linked list back to initial state. linkedList.reverse(); expect(linkedList.toString()).toBe('1,2,3,4'); expect(linkedList.head.previous).toBeNull(); expect(linkedList.head.value).toBe(1); expect(linkedList.head.next.value).toBe(2); expect(linkedList.head.next.next.value).toBe(3); expect(linkedList.head.next.next.next.value).toBe(4); expect(linkedList.tail.next).toBeNull(); expect(linkedList.tail.value).toBe(4); expect(linkedList.tail.previous.value).toBe(3); expect(linkedList.tail.previous.previous.value).toBe(2); expect(linkedList.tail.previous.previous.previous.value).toBe(1); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/doubly-linked-list/__test__/DoublyLinkedListNode.test.js
src/data-structures/doubly-linked-list/__test__/DoublyLinkedListNode.test.js
import DoublyLinkedListNode from '../DoublyLinkedListNode'; describe('DoublyLinkedListNode', () => { it('should create list node with value', () => { const node = new DoublyLinkedListNode(1); expect(node.value).toBe(1); expect(node.next).toBeNull(); expect(node.previous).toBeNull(); }); it('should create list node with object as a value', () => { const nodeValue = { value: 1, key: 'test' }; const node = new DoublyLinkedListNode(nodeValue); expect(node.value.value).toBe(1); expect(node.value.key).toBe('test'); expect(node.next).toBeNull(); expect(node.previous).toBeNull(); }); it('should link nodes together', () => { const node2 = new DoublyLinkedListNode(2); const node1 = new DoublyLinkedListNode(1, node2); const node3 = new DoublyLinkedListNode(10, node1, node2); expect(node1.next).toBeDefined(); expect(node1.previous).toBeNull(); expect(node2.next).toBeNull(); expect(node2.previous).toBeNull(); expect(node3.next).toBeDefined(); expect(node3.previous).toBeDefined(); expect(node1.value).toBe(1); expect(node1.next.value).toBe(2); expect(node3.next.value).toBe(1); expect(node3.previous.value).toBe(2); }); it('should convert node to string', () => { const node = new DoublyLinkedListNode(1); expect(node.toString()).toBe('1'); node.value = 'string value'; expect(node.toString()).toBe('string value'); }); it('should convert node to string with custom stringifier', () => { const nodeValue = { value: 1, key: 'test' }; const node = new DoublyLinkedListNode(nodeValue); const toStringCallback = (value) => `value: ${value.value}, key: ${value.key}`; expect(node.toString(toStringCallback)).toBe('value: 1, key: test'); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/bloom-filter/BloomFilter.js
src/data-structures/bloom-filter/BloomFilter.js
export default class BloomFilter { /** * @param {number} size - the size of the storage. */ constructor(size = 100) { // Bloom filter size directly affects the likelihood of false positives. // The bigger the size the lower the likelihood of false positives. this.size = size; this.storage = this.createStore(size); } /** * @param {string} item */ insert(item) { const hashValues = this.getHashValues(item); // Set each hashValue index to true. hashValues.forEach((val) => this.storage.setValue(val)); } /** * @param {string} item * @return {boolean} */ mayContain(item) { const hashValues = this.getHashValues(item); for (let hashIndex = 0; hashIndex < hashValues.length; hashIndex += 1) { if (!this.storage.getValue(hashValues[hashIndex])) { // We know that the item was definitely not inserted. return false; } } // The item may or may not have been inserted. return true; } /** * Creates the data store for our filter. * We use this method to generate the store in order to * encapsulate the data itself and only provide access * to the necessary methods. * * @param {number} size * @return {Object} */ createStore(size) { const storage = []; // Initialize all indexes to false for (let storageCellIndex = 0; storageCellIndex < size; storageCellIndex += 1) { storage.push(false); } const storageInterface = { getValue(index) { return storage[index]; }, setValue(index) { storage[index] = true; }, }; return storageInterface; } /** * @param {string} item * @return {number} */ hash1(item) { let hash = 0; for (let charIndex = 0; charIndex < item.length; charIndex += 1) { const char = item.charCodeAt(charIndex); hash = (hash << 5) + hash + char; hash &= hash; // Convert to 32bit integer hash = Math.abs(hash); } return hash % this.size; } /** * @param {string} item * @return {number} */ hash2(item) { let hash = 5381; for (let charIndex = 0; charIndex < item.length; charIndex += 1) { const char = item.charCodeAt(charIndex); hash = (hash << 5) + hash + char; /* hash * 33 + c */ } return Math.abs(hash % this.size); } /** * @param {string} item * @return {number} */ hash3(item) { let hash = 0; for (let charIndex = 0; charIndex < item.length; charIndex += 1) { const char = item.charCodeAt(charIndex); hash = (hash << 5) - hash; hash += char; hash &= hash; // Convert to 32bit integer } return Math.abs(hash % this.size); } /** * Runs all 3 hash functions on the input and returns an array of results. * * @param {string} item * @return {number[]} */ getHashValues(item) { return [ this.hash1(item), this.hash2(item), this.hash3(item), ]; } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/bloom-filter/__test__/BloomFilter.test.js
src/data-structures/bloom-filter/__test__/BloomFilter.test.js
import BloomFilter from '../BloomFilter'; describe('BloomFilter', () => { let bloomFilter; const people = [ 'Bruce Wayne', 'Clark Kent', 'Barry Allen', ]; beforeEach(() => { bloomFilter = new BloomFilter(); }); it('should have methods named "insert" and "mayContain"', () => { expect(typeof bloomFilter.insert).toBe('function'); expect(typeof bloomFilter.mayContain).toBe('function'); }); it('should create a new filter store with the appropriate methods', () => { const store = bloomFilter.createStore(18); expect(typeof store.getValue).toBe('function'); expect(typeof store.setValue).toBe('function'); }); it('should hash deterministically with all 3 hash functions', () => { const str1 = 'apple'; expect(bloomFilter.hash1(str1)).toEqual(bloomFilter.hash1(str1)); expect(bloomFilter.hash2(str1)).toEqual(bloomFilter.hash2(str1)); expect(bloomFilter.hash3(str1)).toEqual(bloomFilter.hash3(str1)); expect(bloomFilter.hash1(str1)).toBe(14); expect(bloomFilter.hash2(str1)).toBe(43); expect(bloomFilter.hash3(str1)).toBe(10); const str2 = 'orange'; expect(bloomFilter.hash1(str2)).toEqual(bloomFilter.hash1(str2)); expect(bloomFilter.hash2(str2)).toEqual(bloomFilter.hash2(str2)); expect(bloomFilter.hash3(str2)).toEqual(bloomFilter.hash3(str2)); expect(bloomFilter.hash1(str2)).toBe(0); expect(bloomFilter.hash2(str2)).toBe(61); expect(bloomFilter.hash3(str2)).toBe(10); }); it('should create an array with 3 hash values', () => { expect(bloomFilter.getHashValues('abc').length).toBe(3); expect(bloomFilter.getHashValues('abc')).toEqual([66, 63, 54]); }); it('should insert strings correctly and return true when checking for inserted values', () => { people.forEach((person) => bloomFilter.insert(person)); expect(bloomFilter.mayContain('Bruce Wayne')).toBe(true); expect(bloomFilter.mayContain('Clark Kent')).toBe(true); expect(bloomFilter.mayContain('Barry Allen')).toBe(true); expect(bloomFilter.mayContain('Tony Stark')).toBe(false); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/hash-table/HashTable.js
src/data-structures/hash-table/HashTable.js
import LinkedList from '../linked-list/LinkedList'; // Hash table size directly affects on the number of collisions. // The bigger the hash table size the less collisions you'll get. // For demonstrating purposes hash table size is small to show how collisions // are being handled. const defaultHashTableSize = 32; export default class HashTable { /** * @param {number} hashTableSize */ constructor(hashTableSize = defaultHashTableSize) { // Create hash table of certain size and fill each bucket with empty linked list. this.buckets = Array(hashTableSize).fill(null).map(() => new LinkedList()); // Just to keep track of all actual keys in a fast way. this.keys = {}; } /** * Converts key string to hash number. * * @param {string} key * @return {number} */ hash(key) { // For simplicity reasons we will just use character codes sum of all characters of the key // to calculate the hash. // // But you may also use more sophisticated approaches like polynomial string hash to reduce the // number of collisions: // // hash = charCodeAt(0) * PRIME^(n-1) + charCodeAt(1) * PRIME^(n-2) + ... + charCodeAt(n-1) // // where charCodeAt(i) is the i-th character code of the key, n is the length of the key and // PRIME is just any prime number like 31. const hash = Array.from(key).reduce( (hashAccumulator, keySymbol) => (hashAccumulator + keySymbol.charCodeAt(0)), 0, ); // Reduce hash number so it would fit hash table size. return hash % this.buckets.length; } /** * @param {string} key * @param {*} value */ set(key, value) { const keyHash = this.hash(key); this.keys[key] = keyHash; const bucketLinkedList = this.buckets[keyHash]; const node = bucketLinkedList.find({ callback: (nodeValue) => nodeValue.key === key }); if (!node) { // Insert new node. bucketLinkedList.append({ key, value }); } else { // Update value of existing node. node.value.value = value; } } /** * @param {string} key * @return {*} */ delete(key) { const keyHash = this.hash(key); delete this.keys[key]; const bucketLinkedList = this.buckets[keyHash]; const node = bucketLinkedList.find({ callback: (nodeValue) => nodeValue.key === key }); if (node) { return bucketLinkedList.delete(node.value); } return null; } /** * @param {string} key * @return {*} */ get(key) { const bucketLinkedList = this.buckets[this.hash(key)]; const node = bucketLinkedList.find({ callback: (nodeValue) => nodeValue.key === key }); return node ? node.value.value : undefined; } /** * @param {string} key * @return {boolean} */ has(key) { return Object.hasOwnProperty.call(this.keys, key); } /** * @return {string[]} */ getKeys() { return Object.keys(this.keys); } /** * Gets the list of all the stored values in the hash table. * * @return {*[]} */ getValues() { return this.buckets.reduce((values, bucket) => { const bucketValues = bucket.toArray() .map((linkedListNode) => linkedListNode.value.value); return values.concat(bucketValues); }, []); } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/hash-table/__test__/HashTable.test.js
src/data-structures/hash-table/__test__/HashTable.test.js
import HashTable from '../HashTable'; describe('HashTable', () => { it('should create hash table of certain size', () => { const defaultHashTable = new HashTable(); expect(defaultHashTable.buckets.length).toBe(32); const biggerHashTable = new HashTable(64); expect(biggerHashTable.buckets.length).toBe(64); }); it('should generate proper hash for specified keys', () => { const hashTable = new HashTable(); expect(hashTable.hash('a')).toBe(1); expect(hashTable.hash('b')).toBe(2); expect(hashTable.hash('abc')).toBe(6); }); it('should set, read and delete data with collisions', () => { const hashTable = new HashTable(3); expect(hashTable.hash('a')).toBe(1); expect(hashTable.hash('b')).toBe(2); expect(hashTable.hash('c')).toBe(0); expect(hashTable.hash('d')).toBe(1); hashTable.set('a', 'sky-old'); hashTable.set('a', 'sky'); hashTable.set('b', 'sea'); hashTable.set('c', 'earth'); hashTable.set('d', 'ocean'); expect(hashTable.has('x')).toBe(false); expect(hashTable.has('b')).toBe(true); expect(hashTable.has('c')).toBe(true); const stringifier = (value) => `${value.key}:${value.value}`; expect(hashTable.buckets[0].toString(stringifier)).toBe('c:earth'); expect(hashTable.buckets[1].toString(stringifier)).toBe('a:sky,d:ocean'); expect(hashTable.buckets[2].toString(stringifier)).toBe('b:sea'); expect(hashTable.get('a')).toBe('sky'); expect(hashTable.get('d')).toBe('ocean'); expect(hashTable.get('x')).not.toBeDefined(); hashTable.delete('a'); expect(hashTable.delete('not-existing')).toBeNull(); expect(hashTable.get('a')).not.toBeDefined(); expect(hashTable.get('d')).toBe('ocean'); hashTable.set('d', 'ocean-new'); expect(hashTable.get('d')).toBe('ocean-new'); }); it('should be possible to add objects to hash table', () => { const hashTable = new HashTable(); hashTable.set('objectKey', { prop1: 'a', prop2: 'b' }); const object = hashTable.get('objectKey'); expect(object).toBeDefined(); expect(object.prop1).toBe('a'); expect(object.prop2).toBe('b'); }); it('should track actual keys', () => { const hashTable = new HashTable(3); hashTable.set('a', 'sky-old'); hashTable.set('a', 'sky'); hashTable.set('b', 'sea'); hashTable.set('c', 'earth'); hashTable.set('d', 'ocean'); expect(hashTable.getKeys()).toEqual(['a', 'b', 'c', 'd']); expect(hashTable.has('a')).toBe(true); expect(hashTable.has('x')).toBe(false); hashTable.delete('a'); expect(hashTable.has('a')).toBe(false); expect(hashTable.has('b')).toBe(true); expect(hashTable.has('x')).toBe(false); }); it('should get all the values', () => { const hashTable = new HashTable(3); hashTable.set('a', 'alpha'); hashTable.set('b', 'beta'); hashTable.set('c', 'gamma'); expect(hashTable.getValues()).toEqual(['gamma', 'alpha', 'beta']); }); it('should get all the values from empty hash table', () => { const hashTable = new HashTable(); expect(hashTable.getValues()).toEqual([]); }); it('should get all the values in case of hash collision', () => { const hashTable = new HashTable(3); // Keys `ab` and `ba` in current implementation should result in one hash (one bucket). // We need to make sure that several items from one bucket will be serialized. hashTable.set('ab', 'one'); hashTable.set('ba', 'two'); hashTable.set('ac', 'three'); expect(hashTable.getValues()).toEqual(['one', 'two', 'three']); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/disjoint-set/DisjointSetItem.js
src/data-structures/disjoint-set/DisjointSetItem.js
export default class DisjointSetItem { /** * @param {*} value * @param {function(value: *)} [keyCallback] */ constructor(value, keyCallback) { this.value = value; this.keyCallback = keyCallback; /** @var {DisjointSetItem} this.parent */ this.parent = null; this.children = {}; } /** * @return {*} */ getKey() { // Allow user to define custom key generator. if (this.keyCallback) { return this.keyCallback(this.value); } // Otherwise use value as a key by default. return this.value; } /** * @return {DisjointSetItem} */ getRoot() { return this.isRoot() ? this : this.parent.getRoot(); } /** * @return {boolean} */ isRoot() { return this.parent === null; } /** * Rank basically means the number of all ancestors. * * @return {number} */ getRank() { if (this.getChildren().length === 0) { return 0; } let rank = 0; /** @var {DisjointSetItem} child */ this.getChildren().forEach((child) => { // Count child itself. rank += 1; // Also add all children of current child. rank += child.getRank(); }); return rank; } /** * @return {DisjointSetItem[]} */ getChildren() { return Object.values(this.children); } /** * @param {DisjointSetItem} parentItem * @param {boolean} forceSettingParentChild * @return {DisjointSetItem} */ setParent(parentItem, forceSettingParentChild = true) { this.parent = parentItem; if (forceSettingParentChild) { parentItem.addChild(this); } return this; } /** * @param {DisjointSetItem} childItem * @return {DisjointSetItem} */ addChild(childItem) { this.children[childItem.getKey()] = childItem; childItem.setParent(this, false); return this; } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/disjoint-set/DisjointSetAdhoc.js
src/data-structures/disjoint-set/DisjointSetAdhoc.js
/** * The minimalistic (ad hoc) version of a DisjointSet (or a UnionFind) data structure * that doesn't have external dependencies and that is easy to copy-paste and * use during the coding interview if allowed by the interviewer (since many * data structures in JS are missing). * * Time Complexity: * * - Constructor: O(N) * - Find: O(α(N)) * - Union: O(α(N)) * - Connected: O(α(N)) * * Where N is the number of vertices in the graph. * α refers to the Inverse Ackermann function. * In practice, we assume it's a constant. * In other words, O(α(N)) is regarded as O(1) on average. */ class DisjointSetAdhoc { /** * Initializes the set of specified size. * @param {number} size */ constructor(size) { // The index of a cell is an id of the node in a set. // The value of a cell is an id (index) of the root node. // By default, the node is a parent of itself. this.roots = new Array(size).fill(0).map((_, i) => i); // Using the heights array to record the height of each node. // By default each node has a height of 1 because it has no children. this.heights = new Array(size).fill(1); } /** * Finds the root of node `a` * @param {number} a * @returns {number} */ find(a) { if (a === this.roots[a]) return a; this.roots[a] = this.find(this.roots[a]); return this.roots[a]; } /** * Joins the `a` and `b` nodes into same set. * @param {number} a * @param {number} b * @returns {number} */ union(a, b) { const aRoot = this.find(a); const bRoot = this.find(b); if (aRoot === bRoot) return; if (this.heights[aRoot] > this.heights[bRoot]) { this.roots[bRoot] = aRoot; } else if (this.heights[aRoot] < this.heights[bRoot]) { this.roots[aRoot] = bRoot; } else { this.roots[bRoot] = aRoot; this.heights[aRoot] += 1; } } /** * Checks if `a` and `b` belong to the same set. * @param {number} a * @param {number} b */ connected(a, b) { return this.find(a) === this.find(b); } } export default DisjointSetAdhoc;
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/disjoint-set/DisjointSet.js
src/data-structures/disjoint-set/DisjointSet.js
import DisjointSetItem from './DisjointSetItem'; export default class DisjointSet { /** * @param {function(value: *)} [keyCallback] */ constructor(keyCallback) { this.keyCallback = keyCallback; this.items = {}; } /** * @param {*} itemValue * @return {DisjointSet} */ makeSet(itemValue) { const disjointSetItem = new DisjointSetItem(itemValue, this.keyCallback); if (!this.items[disjointSetItem.getKey()]) { // Add new item only in case if it not presented yet. this.items[disjointSetItem.getKey()] = disjointSetItem; } return this; } /** * Find set representation node. * * @param {*} itemValue * @return {(string|null)} */ find(itemValue) { const templateDisjointItem = new DisjointSetItem(itemValue, this.keyCallback); // Try to find item itself; const requiredDisjointItem = this.items[templateDisjointItem.getKey()]; if (!requiredDisjointItem) { return null; } return requiredDisjointItem.getRoot().getKey(); } /** * Union by rank. * * @param {*} valueA * @param {*} valueB * @return {DisjointSet} */ union(valueA, valueB) { const rootKeyA = this.find(valueA); const rootKeyB = this.find(valueB); if (rootKeyA === null || rootKeyB === null) { throw new Error('One or two values are not in sets'); } if (rootKeyA === rootKeyB) { // In case if both elements are already in the same set then just return its key. return this; } const rootA = this.items[rootKeyA]; const rootB = this.items[rootKeyB]; if (rootA.getRank() < rootB.getRank()) { // If rootB's tree is bigger then make rootB to be a new root. rootB.addChild(rootA); return this; } // If rootA's tree is bigger then make rootA to be a new root. rootA.addChild(rootB); return this; } /** * @param {*} valueA * @param {*} valueB * @return {boolean} */ inSameSet(valueA, valueB) { const rootKeyA = this.find(valueA); const rootKeyB = this.find(valueB); if (rootKeyA === null || rootKeyB === null) { throw new Error('One or two values are not in sets'); } return rootKeyA === rootKeyB; } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/disjoint-set/__test__/DisjointSetItem.test.js
src/data-structures/disjoint-set/__test__/DisjointSetItem.test.js
import DisjointSetItem from '../DisjointSetItem'; describe('DisjointSetItem', () => { it('should do basic manipulation with disjoint set item', () => { const itemA = new DisjointSetItem('A'); const itemB = new DisjointSetItem('B'); const itemC = new DisjointSetItem('C'); const itemD = new DisjointSetItem('D'); expect(itemA.getRank()).toBe(0); expect(itemA.getChildren()).toEqual([]); expect(itemA.getKey()).toBe('A'); expect(itemA.getRoot()).toEqual(itemA); expect(itemA.isRoot()).toBe(true); expect(itemB.isRoot()).toBe(true); itemA.addChild(itemB); itemD.setParent(itemC); expect(itemA.getRank()).toBe(1); expect(itemC.getRank()).toBe(1); expect(itemB.getRank()).toBe(0); expect(itemD.getRank()).toBe(0); expect(itemA.getChildren().length).toBe(1); expect(itemC.getChildren().length).toBe(1); expect(itemA.getChildren()[0]).toEqual(itemB); expect(itemC.getChildren()[0]).toEqual(itemD); expect(itemB.getChildren().length).toBe(0); expect(itemD.getChildren().length).toBe(0); expect(itemA.getRoot()).toEqual(itemA); expect(itemB.getRoot()).toEqual(itemA); expect(itemC.getRoot()).toEqual(itemC); expect(itemD.getRoot()).toEqual(itemC); expect(itemA.isRoot()).toBe(true); expect(itemB.isRoot()).toBe(false); expect(itemC.isRoot()).toBe(true); expect(itemD.isRoot()).toBe(false); itemA.addChild(itemC); expect(itemA.isRoot()).toBe(true); expect(itemB.isRoot()).toBe(false); expect(itemC.isRoot()).toBe(false); expect(itemD.isRoot()).toBe(false); expect(itemA.getRank()).toEqual(3); expect(itemB.getRank()).toEqual(0); expect(itemC.getRank()).toEqual(1); }); it('should do basic manipulation with disjoint set item with custom key extractor', () => { const keyExtractor = (value) => { return value.key; }; const itemA = new DisjointSetItem({ key: 'A', value: 1 }, keyExtractor); const itemB = new DisjointSetItem({ key: 'B', value: 2 }, keyExtractor); const itemC = new DisjointSetItem({ key: 'C', value: 3 }, keyExtractor); const itemD = new DisjointSetItem({ key: 'D', value: 4 }, keyExtractor); expect(itemA.getRank()).toBe(0); expect(itemA.getChildren()).toEqual([]); expect(itemA.getKey()).toBe('A'); expect(itemA.getRoot()).toEqual(itemA); expect(itemA.isRoot()).toBe(true); expect(itemB.isRoot()).toBe(true); itemA.addChild(itemB); itemD.setParent(itemC); expect(itemA.getRank()).toBe(1); expect(itemC.getRank()).toBe(1); expect(itemB.getRank()).toBe(0); expect(itemD.getRank()).toBe(0); expect(itemA.getChildren().length).toBe(1); expect(itemC.getChildren().length).toBe(1); expect(itemA.getChildren()[0]).toEqual(itemB); expect(itemC.getChildren()[0]).toEqual(itemD); expect(itemB.getChildren().length).toBe(0); expect(itemD.getChildren().length).toBe(0); expect(itemA.getRoot()).toEqual(itemA); expect(itemB.getRoot()).toEqual(itemA); expect(itemC.getRoot()).toEqual(itemC); expect(itemD.getRoot()).toEqual(itemC); expect(itemA.isRoot()).toBe(true); expect(itemB.isRoot()).toBe(false); expect(itemC.isRoot()).toBe(true); expect(itemD.isRoot()).toBe(false); itemA.addChild(itemC); expect(itemA.isRoot()).toBe(true); expect(itemB.isRoot()).toBe(false); expect(itemC.isRoot()).toBe(false); expect(itemD.isRoot()).toBe(false); expect(itemA.getRank()).toEqual(3); expect(itemB.getRank()).toEqual(0); expect(itemC.getRank()).toEqual(1); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/disjoint-set/__test__/DisjointSetAdhoc.test.js
src/data-structures/disjoint-set/__test__/DisjointSetAdhoc.test.js
import DisjointSetAdhoc from '../DisjointSetAdhoc'; describe('DisjointSetAdhoc', () => { it('should create unions and find connected elements', () => { const set = new DisjointSetAdhoc(10); // 1-2-5-6-7 3-8-9 4 set.union(1, 2); set.union(2, 5); set.union(5, 6); set.union(6, 7); set.union(3, 8); set.union(8, 9); expect(set.connected(1, 5)).toBe(true); expect(set.connected(5, 7)).toBe(true); expect(set.connected(3, 8)).toBe(true); expect(set.connected(4, 9)).toBe(false); expect(set.connected(4, 7)).toBe(false); // 1-2-5-6-7 3-8-9-4 set.union(9, 4); expect(set.connected(4, 9)).toBe(true); expect(set.connected(4, 3)).toBe(true); expect(set.connected(8, 4)).toBe(true); expect(set.connected(8, 7)).toBe(false); expect(set.connected(2, 3)).toBe(false); }); it('should keep the height of the tree small', () => { const set = new DisjointSetAdhoc(10); // 1-2-6-7-9 1 3 4 5 set.union(7, 6); set.union(1, 2); set.union(2, 6); set.union(1, 7); set.union(9, 1); expect(set.connected(1, 7)).toBe(true); expect(set.connected(6, 9)).toBe(true); expect(set.connected(4, 9)).toBe(false); expect(Math.max(...set.heights)).toBe(3); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/disjoint-set/__test__/DisjointSet.test.js
src/data-structures/disjoint-set/__test__/DisjointSet.test.js
import DisjointSet from '../DisjointSet'; describe('DisjointSet', () => { it('should throw error when trying to union and check not existing sets', () => { function mergeNotExistingSets() { const disjointSet = new DisjointSet(); disjointSet.union('A', 'B'); } function checkNotExistingSets() { const disjointSet = new DisjointSet(); disjointSet.inSameSet('A', 'B'); } expect(mergeNotExistingSets).toThrow(); expect(checkNotExistingSets).toThrow(); }); it('should do basic manipulations on disjoint set', () => { const disjointSet = new DisjointSet(); expect(disjointSet.find('A')).toBeNull(); expect(disjointSet.find('B')).toBeNull(); disjointSet.makeSet('A'); expect(disjointSet.find('A')).toBe('A'); expect(disjointSet.find('B')).toBeNull(); disjointSet.makeSet('B'); expect(disjointSet.find('A')).toBe('A'); expect(disjointSet.find('B')).toBe('B'); disjointSet.makeSet('C'); expect(disjointSet.inSameSet('A', 'B')).toBe(false); disjointSet.union('A', 'B'); expect(disjointSet.find('A')).toBe('A'); expect(disjointSet.find('B')).toBe('A'); expect(disjointSet.inSameSet('A', 'B')).toBe(true); expect(disjointSet.inSameSet('B', 'A')).toBe(true); expect(disjointSet.inSameSet('A', 'C')).toBe(false); disjointSet.union('A', 'A'); disjointSet.union('B', 'C'); expect(disjointSet.find('A')).toBe('A'); expect(disjointSet.find('B')).toBe('A'); expect(disjointSet.find('C')).toBe('A'); expect(disjointSet.inSameSet('A', 'B')).toBe(true); expect(disjointSet.inSameSet('B', 'C')).toBe(true); expect(disjointSet.inSameSet('A', 'C')).toBe(true); disjointSet .makeSet('E') .makeSet('F') .makeSet('G') .makeSet('H') .makeSet('I'); disjointSet .union('E', 'F') .union('F', 'G') .union('G', 'H') .union('H', 'I'); expect(disjointSet.inSameSet('A', 'I')).toBe(false); expect(disjointSet.inSameSet('E', 'I')).toBe(true); disjointSet.union('I', 'C'); expect(disjointSet.find('I')).toBe('E'); expect(disjointSet.inSameSet('A', 'I')).toBe(true); }); it('should union smaller set with bigger one making bigger one to be new root', () => { const disjointSet = new DisjointSet(); disjointSet .makeSet('A') .makeSet('B') .makeSet('C') .union('B', 'C') .union('A', 'C'); expect(disjointSet.find('A')).toBe('B'); }); it('should do basic manipulations on disjoint set with custom key extractor', () => { const keyExtractor = (value) => value.key; const disjointSet = new DisjointSet(keyExtractor); const itemA = { key: 'A', value: 1 }; const itemB = { key: 'B', value: 2 }; const itemC = { key: 'C', value: 3 }; expect(disjointSet.find(itemA)).toBeNull(); expect(disjointSet.find(itemB)).toBeNull(); disjointSet.makeSet(itemA); expect(disjointSet.find(itemA)).toBe('A'); expect(disjointSet.find(itemB)).toBeNull(); disjointSet.makeSet(itemB); expect(disjointSet.find(itemA)).toBe('A'); expect(disjointSet.find(itemB)).toBe('B'); disjointSet.makeSet(itemC); expect(disjointSet.inSameSet(itemA, itemB)).toBe(false); disjointSet.union(itemA, itemB); expect(disjointSet.find(itemA)).toBe('A'); expect(disjointSet.find(itemB)).toBe('A'); expect(disjointSet.inSameSet(itemA, itemB)).toBe(true); expect(disjointSet.inSameSet(itemB, itemA)).toBe(true); expect(disjointSet.inSameSet(itemA, itemC)).toBe(false); disjointSet.union(itemA, itemC); expect(disjointSet.find(itemA)).toBe('A'); expect(disjointSet.find(itemB)).toBe('A'); expect(disjointSet.find(itemC)).toBe('A'); expect(disjointSet.inSameSet(itemA, itemB)).toBe(true); expect(disjointSet.inSameSet(itemB, itemC)).toBe(true); expect(disjointSet.inSameSet(itemA, itemC)).toBe(true); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/tree/BinaryTreeNode.js
src/data-structures/tree/BinaryTreeNode.js
import Comparator from '../../utils/comparator/Comparator'; import HashTable from '../hash-table/HashTable'; export default class BinaryTreeNode { /** * @param {*} [value] - node value. */ constructor(value = null) { this.left = null; this.right = null; this.parent = null; this.value = value; // Any node related meta information may be stored here. this.meta = new HashTable(); // This comparator is used to compare binary tree nodes with each other. this.nodeComparator = new Comparator(); } /** * @return {number} */ get leftHeight() { if (!this.left) { return 0; } return this.left.height + 1; } /** * @return {number} */ get rightHeight() { if (!this.right) { return 0; } return this.right.height + 1; } /** * @return {number} */ get height() { return Math.max(this.leftHeight, this.rightHeight); } /** * @return {number} */ get balanceFactor() { return this.leftHeight - this.rightHeight; } /** * Get parent's sibling if it exists. * @return {BinaryTreeNode} */ get uncle() { // Check if current node has parent. if (!this.parent) { return undefined; } // Check if current node has grand-parent. if (!this.parent.parent) { return undefined; } // Check if grand-parent has two children. if (!this.parent.parent.left || !this.parent.parent.right) { return undefined; } // So for now we know that current node has grand-parent and this // grand-parent has two children. Let's find out who is the uncle. if (this.nodeComparator.equal(this.parent, this.parent.parent.left)) { // Right one is an uncle. return this.parent.parent.right; } // Left one is an uncle. return this.parent.parent.left; } /** * @param {*} value * @return {BinaryTreeNode} */ setValue(value) { this.value = value; return this; } /** * @param {BinaryTreeNode} node * @return {BinaryTreeNode} */ setLeft(node) { // Reset parent for left node since it is going to be detached. if (this.left) { this.left.parent = null; } // Attach new node to the left. this.left = node; // Make current node to be a parent for new left one. if (this.left) { this.left.parent = this; } return this; } /** * @param {BinaryTreeNode} node * @return {BinaryTreeNode} */ setRight(node) { // Reset parent for right node since it is going to be detached. if (this.right) { this.right.parent = null; } // Attach new node to the right. this.right = node; // Make current node to be a parent for new right one. if (node) { this.right.parent = this; } return this; } /** * @param {BinaryTreeNode} nodeToRemove * @return {boolean} */ removeChild(nodeToRemove) { if (this.left && this.nodeComparator.equal(this.left, nodeToRemove)) { this.left = null; return true; } if (this.right && this.nodeComparator.equal(this.right, nodeToRemove)) { this.right = null; return true; } return false; } /** * @param {BinaryTreeNode} nodeToReplace * @param {BinaryTreeNode} replacementNode * @return {boolean} */ replaceChild(nodeToReplace, replacementNode) { if (!nodeToReplace || !replacementNode) { return false; } if (this.left && this.nodeComparator.equal(this.left, nodeToReplace)) { this.left = replacementNode; return true; } if (this.right && this.nodeComparator.equal(this.right, nodeToReplace)) { this.right = replacementNode; return true; } return false; } /** * @param {BinaryTreeNode} sourceNode * @param {BinaryTreeNode} targetNode */ static copyNode(sourceNode, targetNode) { targetNode.setValue(sourceNode.value); targetNode.setLeft(sourceNode.left); targetNode.setRight(sourceNode.right); } /** * @return {*[]} */ traverseInOrder() { let traverse = []; // Add left node. if (this.left) { traverse = traverse.concat(this.left.traverseInOrder()); } // Add root. traverse.push(this.value); // Add right node. if (this.right) { traverse = traverse.concat(this.right.traverseInOrder()); } return traverse; } /** * @return {string} */ toString() { return this.traverseInOrder().toString(); } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/tree/__test__/BinaryTreeNode.test.js
src/data-structures/tree/__test__/BinaryTreeNode.test.js
import BinaryTreeNode from '../BinaryTreeNode'; describe('BinaryTreeNode', () => { it('should create node', () => { const node = new BinaryTreeNode(); expect(node).toBeDefined(); expect(node.value).toBeNull(); expect(node.left).toBeNull(); expect(node.right).toBeNull(); const leftNode = new BinaryTreeNode(1); const rightNode = new BinaryTreeNode(3); const rootNode = new BinaryTreeNode(2); rootNode .setLeft(leftNode) .setRight(rightNode); expect(rootNode.value).toBe(2); expect(rootNode.left.value).toBe(1); expect(rootNode.right.value).toBe(3); }); it('should set parent', () => { const leftNode = new BinaryTreeNode(1); const rightNode = new BinaryTreeNode(3); const rootNode = new BinaryTreeNode(2); rootNode .setLeft(leftNode) .setRight(rightNode); expect(rootNode.parent).toBeNull(); expect(rootNode.left.parent.value).toBe(2); expect(rootNode.right.parent.value).toBe(2); expect(rootNode.right.parent).toEqual(rootNode); }); it('should traverse node', () => { const leftNode = new BinaryTreeNode(1); const rightNode = new BinaryTreeNode(3); const rootNode = new BinaryTreeNode(2); rootNode .setLeft(leftNode) .setRight(rightNode); expect(rootNode.traverseInOrder()).toEqual([1, 2, 3]); expect(rootNode.toString()).toBe('1,2,3'); }); it('should remove child node', () => { const leftNode = new BinaryTreeNode(1); const rightNode = new BinaryTreeNode(3); const rootNode = new BinaryTreeNode(2); rootNode .setLeft(leftNode) .setRight(rightNode); expect(rootNode.traverseInOrder()).toEqual([1, 2, 3]); expect(rootNode.removeChild(rootNode.left)).toBe(true); expect(rootNode.traverseInOrder()).toEqual([2, 3]); expect(rootNode.removeChild(rootNode.right)).toBe(true); expect(rootNode.traverseInOrder()).toEqual([2]); expect(rootNode.removeChild(rootNode.right)).toBe(false); expect(rootNode.traverseInOrder()).toEqual([2]); }); it('should replace child node', () => { const leftNode = new BinaryTreeNode(1); const rightNode = new BinaryTreeNode(3); const rootNode = new BinaryTreeNode(2); rootNode .setLeft(leftNode) .setRight(rightNode); expect(rootNode.traverseInOrder()).toEqual([1, 2, 3]); const replacementNode = new BinaryTreeNode(5); rightNode.setRight(replacementNode); expect(rootNode.traverseInOrder()).toEqual([1, 2, 3, 5]); expect(rootNode.replaceChild(rootNode.right, rootNode.right.right)).toBe(true); expect(rootNode.right.value).toBe(5); expect(rootNode.right.right).toBeNull(); expect(rootNode.traverseInOrder()).toEqual([1, 2, 5]); expect(rootNode.replaceChild(rootNode.right, rootNode.right.right)).toBe(false); expect(rootNode.traverseInOrder()).toEqual([1, 2, 5]); expect(rootNode.replaceChild(rootNode.right, replacementNode)).toBe(true); expect(rootNode.traverseInOrder()).toEqual([1, 2, 5]); expect(rootNode.replaceChild(rootNode.left, replacementNode)).toBe(true); expect(rootNode.traverseInOrder()).toEqual([5, 2, 5]); expect(rootNode.replaceChild(new BinaryTreeNode(), new BinaryTreeNode())).toBe(false); }); it('should calculate node height', () => { const root = new BinaryTreeNode(1); const left = new BinaryTreeNode(3); const right = new BinaryTreeNode(2); const grandLeft = new BinaryTreeNode(5); const grandRight = new BinaryTreeNode(6); const grandGrandLeft = new BinaryTreeNode(7); expect(root.height).toBe(0); expect(root.balanceFactor).toBe(0); root .setLeft(left) .setRight(right); expect(root.height).toBe(1); expect(left.height).toBe(0); expect(root.balanceFactor).toBe(0); left .setLeft(grandLeft) .setRight(grandRight); expect(root.height).toBe(2); expect(left.height).toBe(1); expect(grandLeft.height).toBe(0); expect(grandRight.height).toBe(0); expect(root.balanceFactor).toBe(1); grandLeft.setLeft(grandGrandLeft); expect(root.height).toBe(3); expect(left.height).toBe(2); expect(grandLeft.height).toBe(1); expect(grandRight.height).toBe(0); expect(grandGrandLeft.height).toBe(0); expect(root.balanceFactor).toBe(2); }); it('should calculate node height for right nodes as well', () => { const root = new BinaryTreeNode(1); const right = new BinaryTreeNode(2); root.setRight(right); expect(root.height).toBe(1); expect(right.height).toBe(0); expect(root.balanceFactor).toBe(-1); }); it('should set null for left and right node', () => { const root = new BinaryTreeNode(2); const left = new BinaryTreeNode(1); const right = new BinaryTreeNode(3); root.setLeft(left); root.setRight(right); expect(root.left.value).toBe(1); expect(root.right.value).toBe(3); root.setLeft(null); root.setRight(null); expect(root.left).toBeNull(); expect(root.right).toBeNull(); }); it('should be possible to create node with object as a value', () => { const obj1 = { key: 'object_1', toString: () => 'object_1' }; const obj2 = { key: 'object_2' }; const node1 = new BinaryTreeNode(obj1); const node2 = new BinaryTreeNode(obj2); node1.setLeft(node2); expect(node1.value).toEqual(obj1); expect(node2.value).toEqual(obj2); expect(node1.left.value).toEqual(obj2); node1.removeChild(node2); expect(node1.value).toEqual(obj1); expect(node2.value).toEqual(obj2); expect(node1.left).toBeNull(); expect(node1.toString()).toBe('object_1'); expect(node2.toString()).toBe('[object Object]'); }); it('should be possible to attach meta information to the node', () => { const redNode = new BinaryTreeNode(1); const blackNode = new BinaryTreeNode(2); redNode.meta.set('color', 'red'); blackNode.meta.set('color', 'black'); expect(redNode.meta.get('color')).toBe('red'); expect(blackNode.meta.get('color')).toBe('black'); }); it('should detect right uncle', () => { const grandParent = new BinaryTreeNode('grand-parent'); const parent = new BinaryTreeNode('parent'); const uncle = new BinaryTreeNode('uncle'); const child = new BinaryTreeNode('child'); expect(grandParent.uncle).not.toBeDefined(); expect(parent.uncle).not.toBeDefined(); grandParent.setLeft(parent); expect(parent.uncle).not.toBeDefined(); expect(child.uncle).not.toBeDefined(); parent.setLeft(child); expect(child.uncle).not.toBeDefined(); grandParent.setRight(uncle); expect(parent.uncle).not.toBeDefined(); expect(child.uncle).toBeDefined(); expect(child.uncle).toEqual(uncle); }); it('should detect left uncle', () => { const grandParent = new BinaryTreeNode('grand-parent'); const parent = new BinaryTreeNode('parent'); const uncle = new BinaryTreeNode('uncle'); const child = new BinaryTreeNode('child'); expect(grandParent.uncle).not.toBeDefined(); expect(parent.uncle).not.toBeDefined(); grandParent.setRight(parent); expect(parent.uncle).not.toBeDefined(); expect(child.uncle).not.toBeDefined(); parent.setRight(child); expect(child.uncle).not.toBeDefined(); grandParent.setLeft(uncle); expect(parent.uncle).not.toBeDefined(); expect(child.uncle).toBeDefined(); expect(child.uncle).toEqual(uncle); }); it('should be possible to set node values', () => { const node = new BinaryTreeNode('initial_value'); expect(node.value).toBe('initial_value'); node.setValue('new_value'); expect(node.value).toBe('new_value'); }); it('should be possible to copy node', () => { const root = new BinaryTreeNode('root'); const left = new BinaryTreeNode('left'); const right = new BinaryTreeNode('right'); root .setLeft(left) .setRight(right); expect(root.toString()).toBe('left,root,right'); const newRoot = new BinaryTreeNode('new_root'); const newLeft = new BinaryTreeNode('new_left'); const newRight = new BinaryTreeNode('new_right'); newRoot .setLeft(newLeft) .setRight(newRight); expect(newRoot.toString()).toBe('new_left,new_root,new_right'); BinaryTreeNode.copyNode(root, newRoot); expect(root.toString()).toBe('left,root,right'); expect(newRoot.toString()).toBe('left,root,right'); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/tree/avl-tree/AvlTree.js
src/data-structures/tree/avl-tree/AvlTree.js
import BinarySearchTree from '../binary-search-tree/BinarySearchTree'; export default class AvlTree extends BinarySearchTree { /** * @param {*} value */ insert(value) { // Do the normal BST insert. super.insert(value); // Let's move up to the root and check balance factors along the way. let currentNode = this.root.find(value); while (currentNode) { this.balance(currentNode); currentNode = currentNode.parent; } } /** * @param {*} value * @return {boolean} */ remove(value) { // Do standard BST removal. super.remove(value); // Balance the tree starting from the root node. this.balance(this.root); } /** * @param {BinarySearchTreeNode} node */ balance(node) { // If balance factor is not OK then try to balance the node. if (node.balanceFactor > 1) { // Left rotation. if (node.left.balanceFactor > 0) { // Left-Left rotation this.rotateLeftLeft(node); } else if (node.left.balanceFactor < 0) { // Left-Right rotation. this.rotateLeftRight(node); } } else if (node.balanceFactor < -1) { // Right rotation. if (node.right.balanceFactor < 0) { // Right-Right rotation this.rotateRightRight(node); } else if (node.right.balanceFactor > 0) { // Right-Left rotation. this.rotateRightLeft(node); } } } /** * @param {BinarySearchTreeNode} rootNode */ rotateLeftLeft(rootNode) { // Detach left node from root node. const leftNode = rootNode.left; rootNode.setLeft(null); // Make left node to be a child of rootNode's parent. if (rootNode.parent) { rootNode.parent.setLeft(leftNode); } else if (rootNode === this.root) { // If root node is root then make left node to be a new root. this.root = leftNode; } // If left node has a right child then detach it and // attach it as a left child for rootNode. if (leftNode.right) { rootNode.setLeft(leftNode.right); } // Attach rootNode to the right of leftNode. leftNode.setRight(rootNode); } /** * @param {BinarySearchTreeNode} rootNode */ rotateLeftRight(rootNode) { // Detach left node from rootNode since it is going to be replaced. const leftNode = rootNode.left; rootNode.setLeft(null); // Detach right node from leftNode. const leftRightNode = leftNode.right; leftNode.setRight(null); // Preserve leftRightNode's left subtree. if (leftRightNode.left) { leftNode.setRight(leftRightNode.left); leftRightNode.setLeft(null); } // Attach leftRightNode to the rootNode. rootNode.setLeft(leftRightNode); // Attach leftNode as left node for leftRight node. leftRightNode.setLeft(leftNode); // Do left-left rotation. this.rotateLeftLeft(rootNode); } /** * @param {BinarySearchTreeNode} rootNode */ rotateRightLeft(rootNode) { // Detach right node from rootNode since it is going to be replaced. const rightNode = rootNode.right; rootNode.setRight(null); // Detach left node from rightNode. const rightLeftNode = rightNode.left; rightNode.setLeft(null); if (rightLeftNode.right) { rightNode.setLeft(rightLeftNode.right); rightLeftNode.setRight(null); } // Attach rightLeftNode to the rootNode. rootNode.setRight(rightLeftNode); // Attach rightNode as right node for rightLeft node. rightLeftNode.setRight(rightNode); // Do right-right rotation. this.rotateRightRight(rootNode); } /** * @param {BinarySearchTreeNode} rootNode */ rotateRightRight(rootNode) { // Detach right node from root node. const rightNode = rootNode.right; rootNode.setRight(null); // Make right node to be a child of rootNode's parent. if (rootNode.parent) { rootNode.parent.setRight(rightNode); } else if (rootNode === this.root) { // If root node is root then make right node to be a new root. this.root = rightNode; } // If right node has a left child then detach it and // attach it as a right child for rootNode. if (rightNode.left) { rootNode.setRight(rightNode.left); } // Attach rootNode to the left of rightNode. rightNode.setLeft(rootNode); } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/tree/avl-tree/__test__/AvlTRee.test.js
src/data-structures/tree/avl-tree/__test__/AvlTRee.test.js
import AvlTree from '../AvlTree'; describe('AvlTree', () => { it('should do simple left-left rotation', () => { const tree = new AvlTree(); tree.insert(4); tree.insert(3); tree.insert(2); expect(tree.toString()).toBe('2,3,4'); expect(tree.root.value).toBe(3); expect(tree.root.height).toBe(1); tree.insert(1); expect(tree.toString()).toBe('1,2,3,4'); expect(tree.root.value).toBe(3); expect(tree.root.height).toBe(2); tree.insert(0); expect(tree.toString()).toBe('0,1,2,3,4'); expect(tree.root.value).toBe(3); expect(tree.root.left.value).toBe(1); expect(tree.root.height).toBe(2); }); it('should do complex left-left rotation', () => { const tree = new AvlTree(); tree.insert(30); tree.insert(20); tree.insert(40); tree.insert(10); expect(tree.root.value).toBe(30); expect(tree.root.height).toBe(2); expect(tree.toString()).toBe('10,20,30,40'); tree.insert(25); expect(tree.root.value).toBe(30); expect(tree.root.height).toBe(2); expect(tree.toString()).toBe('10,20,25,30,40'); tree.insert(5); expect(tree.root.value).toBe(20); expect(tree.root.height).toBe(2); expect(tree.toString()).toBe('5,10,20,25,30,40'); }); it('should do simple right-right rotation', () => { const tree = new AvlTree(); tree.insert(2); tree.insert(3); tree.insert(4); expect(tree.toString()).toBe('2,3,4'); expect(tree.root.value).toBe(3); expect(tree.root.height).toBe(1); tree.insert(5); expect(tree.toString()).toBe('2,3,4,5'); expect(tree.root.value).toBe(3); expect(tree.root.height).toBe(2); tree.insert(6); expect(tree.toString()).toBe('2,3,4,5,6'); expect(tree.root.value).toBe(3); expect(tree.root.right.value).toBe(5); expect(tree.root.height).toBe(2); }); it('should do complex right-right rotation', () => { const tree = new AvlTree(); tree.insert(30); tree.insert(20); tree.insert(40); tree.insert(50); expect(tree.root.value).toBe(30); expect(tree.root.height).toBe(2); expect(tree.toString()).toBe('20,30,40,50'); tree.insert(35); expect(tree.root.value).toBe(30); expect(tree.root.height).toBe(2); expect(tree.toString()).toBe('20,30,35,40,50'); tree.insert(55); expect(tree.root.value).toBe(40); expect(tree.root.height).toBe(2); expect(tree.toString()).toBe('20,30,35,40,50,55'); }); it('should do left-right rotation', () => { const tree = new AvlTree(); tree.insert(30); tree.insert(20); tree.insert(25); expect(tree.root.height).toBe(1); expect(tree.root.value).toBe(25); expect(tree.toString()).toBe('20,25,30'); }); it('should do right-left rotation', () => { const tree = new AvlTree(); tree.insert(30); tree.insert(40); tree.insert(35); expect(tree.root.height).toBe(1); expect(tree.root.value).toBe(35); expect(tree.toString()).toBe('30,35,40'); }); it('should create balanced tree: case #1', () => { // @see: https://www.youtube.com/watch?v=rbg7Qf8GkQ4&t=839s const tree = new AvlTree(); tree.insert(1); tree.insert(2); tree.insert(3); expect(tree.root.value).toBe(2); expect(tree.root.height).toBe(1); expect(tree.toString()).toBe('1,2,3'); tree.insert(6); expect(tree.root.value).toBe(2); expect(tree.root.height).toBe(2); expect(tree.toString()).toBe('1,2,3,6'); tree.insert(15); expect(tree.root.value).toBe(2); expect(tree.root.height).toBe(2); expect(tree.toString()).toBe('1,2,3,6,15'); tree.insert(-2); expect(tree.root.value).toBe(2); expect(tree.root.height).toBe(2); expect(tree.toString()).toBe('-2,1,2,3,6,15'); tree.insert(-5); expect(tree.root.value).toBe(2); expect(tree.root.height).toBe(2); expect(tree.toString()).toBe('-5,-2,1,2,3,6,15'); tree.insert(-8); expect(tree.root.value).toBe(2); expect(tree.root.height).toBe(3); expect(tree.toString()).toBe('-8,-5,-2,1,2,3,6,15'); }); it('should create balanced tree: case #2', () => { // @see https://www.youtube.com/watch?v=7m94k2Qhg68 const tree = new AvlTree(); tree.insert(43); tree.insert(18); tree.insert(22); tree.insert(9); tree.insert(21); tree.insert(6); expect(tree.root.value).toBe(18); expect(tree.root.height).toBe(2); expect(tree.toString()).toBe('6,9,18,21,22,43'); tree.insert(8); expect(tree.root.value).toBe(18); expect(tree.root.height).toBe(2); expect(tree.toString()).toBe('6,8,9,18,21,22,43'); }); it('should do left right rotation and keeping left right node safe', () => { const tree = new AvlTree(); tree.insert(30); tree.insert(15); tree.insert(40); tree.insert(10); tree.insert(18); tree.insert(35); tree.insert(45); tree.insert(5); tree.insert(12); expect(tree.toString()).toBe('5,10,12,15,18,30,35,40,45'); expect(tree.root.height).toBe(3); tree.insert(11); expect(tree.toString()).toBe('5,10,11,12,15,18,30,35,40,45'); expect(tree.root.height).toBe(3); }); it('should do left right rotation and keeping left right node safe', () => { const tree = new AvlTree(); tree.insert(30); tree.insert(15); tree.insert(40); tree.insert(10); tree.insert(18); tree.insert(35); tree.insert(45); tree.insert(42); tree.insert(47); expect(tree.toString()).toBe('10,15,18,30,35,40,42,45,47'); expect(tree.root.height).toBe(3); tree.insert(43); expect(tree.toString()).toBe('10,15,18,30,35,40,42,43,45,47'); expect(tree.root.height).toBe(3); }); it('should remove values from the tree with right-right rotation', () => { const tree = new AvlTree(); tree.insert(10); tree.insert(20); tree.insert(30); tree.insert(40); expect(tree.toString()).toBe('10,20,30,40'); tree.remove(10); expect(tree.toString()).toBe('20,30,40'); expect(tree.root.value).toBe(30); expect(tree.root.left.value).toBe(20); expect(tree.root.right.value).toBe(40); expect(tree.root.balanceFactor).toBe(0); }); it('should remove values from the tree with left-left rotation', () => { const tree = new AvlTree(); tree.insert(10); tree.insert(20); tree.insert(30); tree.insert(5); expect(tree.toString()).toBe('5,10,20,30'); tree.remove(30); expect(tree.toString()).toBe('5,10,20'); expect(tree.root.value).toBe(10); expect(tree.root.left.value).toBe(5); expect(tree.root.right.value).toBe(20); expect(tree.root.balanceFactor).toBe(0); }); it('should keep balance after removal', () => { const tree = new AvlTree(); tree.insert(1); tree.insert(2); tree.insert(3); tree.insert(4); tree.insert(5); tree.insert(6); tree.insert(7); tree.insert(8); tree.insert(9); expect(tree.toString()).toBe('1,2,3,4,5,6,7,8,9'); expect(tree.root.value).toBe(4); expect(tree.root.height).toBe(3); expect(tree.root.balanceFactor).toBe(-1); tree.remove(8); expect(tree.root.value).toBe(4); expect(tree.root.balanceFactor).toBe(-1); tree.remove(9); expect(tree.contains(8)).toBeFalsy(); expect(tree.contains(9)).toBeFalsy(); expect(tree.toString()).toBe('1,2,3,4,5,6,7'); expect(tree.root.value).toBe(4); expect(tree.root.height).toBe(2); expect(tree.root.balanceFactor).toBe(0); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/tree/fenwick-tree/FenwickTree.js
src/data-structures/tree/fenwick-tree/FenwickTree.js
export default class FenwickTree { /** * Constructor creates empty fenwick tree of size 'arraySize', * however, array size is size+1, because index is 1-based. * * @param {number} arraySize */ constructor(arraySize) { this.arraySize = arraySize; // Fill tree array with zeros. this.treeArray = Array(this.arraySize + 1).fill(0); } /** * Adds value to existing value at position. * * @param {number} position * @param {number} value * @return {FenwickTree} */ increase(position, value) { if (position < 1 || position > this.arraySize) { throw new Error('Position is out of allowed range'); } for (let i = position; i <= this.arraySize; i += (i & -i)) { this.treeArray[i] += value; } return this; } /** * Query sum from index 1 to position. * * @param {number} position * @return {number} */ query(position) { if (position < 1 || position > this.arraySize) { throw new Error('Position is out of allowed range'); } let sum = 0; for (let i = position; i > 0; i -= (i & -i)) { sum += this.treeArray[i]; } return sum; } /** * Query sum from index leftIndex to rightIndex. * * @param {number} leftIndex * @param {number} rightIndex * @return {number} */ queryRange(leftIndex, rightIndex) { if (leftIndex > rightIndex) { throw new Error('Left index can not be greater than right one'); } if (leftIndex === 1) { return this.query(rightIndex); } return this.query(rightIndex) - this.query(leftIndex - 1); } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/tree/fenwick-tree/__test__/FenwickTree.test.js
src/data-structures/tree/fenwick-tree/__test__/FenwickTree.test.js
import FenwickTree from '../FenwickTree'; describe('FenwickTree', () => { it('should create empty fenwick tree of correct size', () => { const tree1 = new FenwickTree(5); expect(tree1.treeArray.length).toBe(5 + 1); for (let i = 0; i < 5; i += 1) { expect(tree1.treeArray[i]).toBe(0); } const tree2 = new FenwickTree(50); expect(tree2.treeArray.length).toBe(50 + 1); }); it('should create correct fenwick tree', () => { const inputArray = [3, 2, -1, 6, 5, 4, -3, 3, 7, 2, 3]; const tree = new FenwickTree(inputArray.length); expect(tree.treeArray.length).toBe(inputArray.length + 1); inputArray.forEach((value, index) => { tree.increase(index + 1, value); }); expect(tree.treeArray).toEqual([0, 3, 5, -1, 10, 5, 9, -3, 19, 7, 9, 3]); expect(tree.query(1)).toBe(3); expect(tree.query(2)).toBe(5); expect(tree.query(3)).toBe(4); expect(tree.query(4)).toBe(10); expect(tree.query(5)).toBe(15); expect(tree.query(6)).toBe(19); expect(tree.query(7)).toBe(16); expect(tree.query(8)).toBe(19); expect(tree.query(9)).toBe(26); expect(tree.query(10)).toBe(28); expect(tree.query(11)).toBe(31); expect(tree.queryRange(1, 1)).toBe(3); expect(tree.queryRange(1, 2)).toBe(5); expect(tree.queryRange(2, 4)).toBe(7); expect(tree.queryRange(6, 9)).toBe(11); tree.increase(3, 1); expect(tree.query(1)).toBe(3); expect(tree.query(2)).toBe(5); expect(tree.query(3)).toBe(5); expect(tree.query(4)).toBe(11); expect(tree.query(5)).toBe(16); expect(tree.query(6)).toBe(20); expect(tree.query(7)).toBe(17); expect(tree.query(8)).toBe(20); expect(tree.query(9)).toBe(27); expect(tree.query(10)).toBe(29); expect(tree.query(11)).toBe(32); expect(tree.queryRange(1, 1)).toBe(3); expect(tree.queryRange(1, 2)).toBe(5); expect(tree.queryRange(2, 4)).toBe(8); expect(tree.queryRange(6, 9)).toBe(11); }); it('should correctly execute queries', () => { const tree = new FenwickTree(5); tree.increase(1, 4); tree.increase(3, 7); expect(tree.query(1)).toBe(4); expect(tree.query(3)).toBe(11); expect(tree.query(5)).toBe(11); expect(tree.queryRange(2, 3)).toBe(7); tree.increase(2, 5); expect(tree.query(5)).toBe(16); tree.increase(1, 3); expect(tree.queryRange(1, 1)).toBe(7); expect(tree.query(5)).toBe(19); expect(tree.queryRange(1, 5)).toBe(19); }); it('should throw exceptions', () => { const tree = new FenwickTree(5); const increaseAtInvalidLowIndex = () => { tree.increase(0, 1); }; const increaseAtInvalidHighIndex = () => { tree.increase(10, 1); }; const queryInvalidLowIndex = () => { tree.query(0); }; const queryInvalidHighIndex = () => { tree.query(10); }; const rangeQueryInvalidIndex = () => { tree.queryRange(3, 2); }; expect(increaseAtInvalidLowIndex).toThrowError(); expect(increaseAtInvalidHighIndex).toThrowError(); expect(queryInvalidLowIndex).toThrowError(); expect(queryInvalidHighIndex).toThrowError(); expect(rangeQueryInvalidIndex).toThrowError(); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/tree/binary-search-tree/BinarySearchTreeNode.js
src/data-structures/tree/binary-search-tree/BinarySearchTreeNode.js
import BinaryTreeNode from '../BinaryTreeNode'; import Comparator from '../../../utils/comparator/Comparator'; export default class BinarySearchTreeNode extends BinaryTreeNode { /** * @param {*} [value] - node value. * @param {function} [compareFunction] - comparator function for node values. */ constructor(value = null, compareFunction = undefined) { super(value); // This comparator is used to compare node values with each other. this.compareFunction = compareFunction; this.nodeValueComparator = new Comparator(compareFunction); } /** * @param {*} value * @return {BinarySearchTreeNode} */ insert(value) { if (this.nodeValueComparator.equal(this.value, null)) { this.value = value; return this; } if (this.nodeValueComparator.lessThan(value, this.value)) { // Insert to the left. if (this.left) { return this.left.insert(value); } const newNode = new BinarySearchTreeNode(value, this.compareFunction); this.setLeft(newNode); return newNode; } if (this.nodeValueComparator.greaterThan(value, this.value)) { // Insert to the right. if (this.right) { return this.right.insert(value); } const newNode = new BinarySearchTreeNode(value, this.compareFunction); this.setRight(newNode); return newNode; } return this; } /** * @param {*} value * @return {BinarySearchTreeNode} */ find(value) { // Check the root. if (this.nodeValueComparator.equal(this.value, value)) { return this; } if (this.nodeValueComparator.lessThan(value, this.value) && this.left) { // Check left nodes. return this.left.find(value); } if (this.nodeValueComparator.greaterThan(value, this.value) && this.right) { // Check right nodes. return this.right.find(value); } return null; } /** * @param {*} value * @return {boolean} */ contains(value) { return !!this.find(value); } /** * @param {*} value * @return {boolean} */ remove(value) { const nodeToRemove = this.find(value); if (!nodeToRemove) { throw new Error('Item not found in the tree'); } const { parent } = nodeToRemove; if (!nodeToRemove.left && !nodeToRemove.right) { // Node is a leaf and thus has no children. if (parent) { // Node has a parent. Just remove the pointer to this node from the parent. parent.removeChild(nodeToRemove); } else { // Node has no parent. Just erase current node value. nodeToRemove.setValue(undefined); } } else if (nodeToRemove.left && nodeToRemove.right) { // Node has two children. // Find the next biggest value (minimum value in the right branch) // and replace current value node with that next biggest value. const nextBiggerNode = nodeToRemove.right.findMin(); if (!this.nodeComparator.equal(nextBiggerNode, nodeToRemove.right)) { this.remove(nextBiggerNode.value); nodeToRemove.setValue(nextBiggerNode.value); } else { // In case if next right value is the next bigger one and it doesn't have left child // then just replace node that is going to be deleted with the right node. nodeToRemove.setValue(nodeToRemove.right.value); nodeToRemove.setRight(nodeToRemove.right.right); } } else { // Node has only one child. // Make this child to be a direct child of current node's parent. /** @var BinarySearchTreeNode */ const childNode = nodeToRemove.left || nodeToRemove.right; if (parent) { parent.replaceChild(nodeToRemove, childNode); } else { BinaryTreeNode.copyNode(childNode, nodeToRemove); } } // Clear the parent of removed node. nodeToRemove.parent = null; return true; } /** * @return {BinarySearchTreeNode} */ findMin() { if (!this.left) { return this; } return this.left.findMin(); } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/tree/binary-search-tree/BinarySearchTree.js
src/data-structures/tree/binary-search-tree/BinarySearchTree.js
import BinarySearchTreeNode from './BinarySearchTreeNode'; export default class BinarySearchTree { /** * @param {function} [nodeValueCompareFunction] */ constructor(nodeValueCompareFunction) { this.root = new BinarySearchTreeNode(null, nodeValueCompareFunction); // Steal node comparator from the root. this.nodeComparator = this.root.nodeComparator; } /** * @param {*} value * @return {BinarySearchTreeNode} */ insert(value) { return this.root.insert(value); } /** * @param {*} value * @return {boolean} */ contains(value) { return this.root.contains(value); } /** * @param {*} value * @return {boolean} */ remove(value) { return this.root.remove(value); } /** * @return {string} */ toString() { return this.root.toString(); } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/tree/binary-search-tree/__test__/BinarySearchTreeNode.test.js
src/data-structures/tree/binary-search-tree/__test__/BinarySearchTreeNode.test.js
import BinarySearchTreeNode from '../BinarySearchTreeNode'; describe('BinarySearchTreeNode', () => { it('should create binary search tree', () => { const bstNode = new BinarySearchTreeNode(2); expect(bstNode.value).toBe(2); expect(bstNode.left).toBeNull(); expect(bstNode.right).toBeNull(); }); it('should insert in itself if it is empty', () => { const bstNode = new BinarySearchTreeNode(); bstNode.insert(1); expect(bstNode.value).toBe(1); expect(bstNode.left).toBeNull(); expect(bstNode.right).toBeNull(); }); it('should insert nodes in correct order', () => { const bstNode = new BinarySearchTreeNode(2); const insertedNode1 = bstNode.insert(1); expect(insertedNode1.value).toBe(1); expect(bstNode.toString()).toBe('1,2'); expect(bstNode.contains(1)).toBe(true); expect(bstNode.contains(3)).toBe(false); const insertedNode2 = bstNode.insert(3); expect(insertedNode2.value).toBe(3); expect(bstNode.toString()).toBe('1,2,3'); expect(bstNode.contains(3)).toBe(true); expect(bstNode.contains(4)).toBe(false); bstNode.insert(7); expect(bstNode.toString()).toBe('1,2,3,7'); expect(bstNode.contains(7)).toBe(true); expect(bstNode.contains(8)).toBe(false); bstNode.insert(4); expect(bstNode.toString()).toBe('1,2,3,4,7'); expect(bstNode.contains(4)).toBe(true); expect(bstNode.contains(8)).toBe(false); bstNode.insert(6); expect(bstNode.toString()).toBe('1,2,3,4,6,7'); expect(bstNode.contains(6)).toBe(true); expect(bstNode.contains(8)).toBe(false); }); it('should not insert duplicates', () => { const bstNode = new BinarySearchTreeNode(2); bstNode.insert(1); expect(bstNode.toString()).toBe('1,2'); expect(bstNode.contains(1)).toBe(true); expect(bstNode.contains(3)).toBe(false); bstNode.insert(1); expect(bstNode.toString()).toBe('1,2'); expect(bstNode.contains(1)).toBe(true); expect(bstNode.contains(3)).toBe(false); }); it('should find min node', () => { const node = new BinarySearchTreeNode(10); node.insert(20); node.insert(30); node.insert(5); node.insert(40); node.insert(1); expect(node.findMin()).not.toBeNull(); expect(node.findMin().value).toBe(1); }); it('should be possible to attach meta information to binary search tree nodes', () => { const node = new BinarySearchTreeNode(10); node.insert(20); const node1 = node.insert(30); node.insert(5); node.insert(40); const node2 = node.insert(1); node.meta.set('color', 'red'); node1.meta.set('color', 'black'); node2.meta.set('color', 'white'); expect(node.meta.get('color')).toBe('red'); expect(node.findMin()).not.toBeNull(); expect(node.findMin().value).toBe(1); expect(node.findMin().meta.get('color')).toBe('white'); expect(node.find(30).meta.get('color')).toBe('black'); }); it('should find node', () => { const node = new BinarySearchTreeNode(10); node.insert(20); node.insert(30); node.insert(5); node.insert(40); node.insert(1); expect(node.find(6)).toBeNull(); expect(node.find(5)).not.toBeNull(); expect(node.find(5).value).toBe(5); }); it('should remove leaf nodes', () => { const bstRootNode = new BinarySearchTreeNode(); bstRootNode.insert(10); bstRootNode.insert(20); bstRootNode.insert(5); expect(bstRootNode.toString()).toBe('5,10,20'); const removed1 = bstRootNode.remove(5); expect(bstRootNode.toString()).toBe('10,20'); expect(removed1).toBe(true); const removed2 = bstRootNode.remove(20); expect(bstRootNode.toString()).toBe('10'); expect(removed2).toBe(true); }); it('should remove nodes with one child', () => { const bstRootNode = new BinarySearchTreeNode(); bstRootNode.insert(10); bstRootNode.insert(20); bstRootNode.insert(5); bstRootNode.insert(30); expect(bstRootNode.toString()).toBe('5,10,20,30'); bstRootNode.remove(20); expect(bstRootNode.toString()).toBe('5,10,30'); bstRootNode.insert(1); expect(bstRootNode.toString()).toBe('1,5,10,30'); bstRootNode.remove(5); expect(bstRootNode.toString()).toBe('1,10,30'); }); it('should remove nodes with two children', () => { const bstRootNode = new BinarySearchTreeNode(); bstRootNode.insert(10); bstRootNode.insert(20); bstRootNode.insert(5); bstRootNode.insert(30); bstRootNode.insert(15); bstRootNode.insert(25); expect(bstRootNode.toString()).toBe('5,10,15,20,25,30'); expect(bstRootNode.find(20).left.value).toBe(15); expect(bstRootNode.find(20).right.value).toBe(30); bstRootNode.remove(20); expect(bstRootNode.toString()).toBe('5,10,15,25,30'); bstRootNode.remove(15); expect(bstRootNode.toString()).toBe('5,10,25,30'); bstRootNode.remove(10); expect(bstRootNode.toString()).toBe('5,25,30'); expect(bstRootNode.value).toBe(25); bstRootNode.remove(25); expect(bstRootNode.toString()).toBe('5,30'); bstRootNode.remove(5); expect(bstRootNode.toString()).toBe('30'); }); it('should remove node with no parent', () => { const bstRootNode = new BinarySearchTreeNode(); expect(bstRootNode.toString()).toBe(''); bstRootNode.insert(1); bstRootNode.insert(2); expect(bstRootNode.toString()).toBe('1,2'); bstRootNode.remove(1); expect(bstRootNode.toString()).toBe('2'); bstRootNode.remove(2); expect(bstRootNode.toString()).toBe(''); }); it('should throw error when trying to remove not existing node', () => { const bstRootNode = new BinarySearchTreeNode(); bstRootNode.insert(10); bstRootNode.insert(20); function removeNotExistingElementFromTree() { bstRootNode.remove(30); } expect(removeNotExistingElementFromTree).toThrow(); }); it('should be possible to use objects as node values', () => { const nodeValueComparatorCallback = (a, b) => { const normalizedA = a || { value: null }; const normalizedB = b || { value: null }; if (normalizedA.value === normalizedB.value) { return 0; } return normalizedA.value < normalizedB.value ? -1 : 1; }; const obj1 = { key: 'obj1', value: 1, toString: () => 'obj1' }; const obj2 = { key: 'obj2', value: 2, toString: () => 'obj2' }; const obj3 = { key: 'obj3', value: 3, toString: () => 'obj3' }; const bstNode = new BinarySearchTreeNode(obj2, nodeValueComparatorCallback); bstNode.insert(obj1); expect(bstNode.toString()).toBe('obj1,obj2'); expect(bstNode.contains(obj1)).toBe(true); expect(bstNode.contains(obj3)).toBe(false); bstNode.insert(obj3); expect(bstNode.toString()).toBe('obj1,obj2,obj3'); expect(bstNode.contains(obj3)).toBe(true); expect(bstNode.findMin().value).toEqual(obj1); }); it('should abandon removed node', () => { const rootNode = new BinarySearchTreeNode('foo'); rootNode.insert('bar'); const childNode = rootNode.find('bar'); rootNode.remove('bar'); expect(childNode.parent).toBeNull(); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/tree/binary-search-tree/__test__/BinarySearchTree.test.js
src/data-structures/tree/binary-search-tree/__test__/BinarySearchTree.test.js
import BinarySearchTree from '../BinarySearchTree'; describe('BinarySearchTree', () => { it('should create binary search tree', () => { const bst = new BinarySearchTree(); expect(bst).toBeDefined(); expect(bst.root).toBeDefined(); expect(bst.root.value).toBeNull(); expect(bst.root.left).toBeNull(); expect(bst.root.right).toBeNull(); }); it('should insert values', () => { const bst = new BinarySearchTree(); const insertedNode1 = bst.insert(10); const insertedNode2 = bst.insert(20); bst.insert(5); expect(bst.toString()).toBe('5,10,20'); expect(insertedNode1.value).toBe(10); expect(insertedNode2.value).toBe(20); }); it('should check if value exists', () => { const bst = new BinarySearchTree(); bst.insert(10); bst.insert(20); bst.insert(5); expect(bst.contains(20)).toBe(true); expect(bst.contains(40)).toBe(false); }); it('should remove nodes', () => { const bst = new BinarySearchTree(); bst.insert(10); bst.insert(20); bst.insert(5); expect(bst.toString()).toBe('5,10,20'); const removed1 = bst.remove(5); expect(bst.toString()).toBe('10,20'); expect(removed1).toBe(true); const removed2 = bst.remove(20); expect(bst.toString()).toBe('10'); expect(removed2).toBe(true); }); it('should insert object values', () => { const nodeValueCompareFunction = (a, b) => { const normalizedA = a || { value: null }; const normalizedB = b || { value: null }; if (normalizedA.value === normalizedB.value) { return 0; } return normalizedA.value < normalizedB.value ? -1 : 1; }; const obj1 = { key: 'obj1', value: 1, toString: () => 'obj1' }; const obj2 = { key: 'obj2', value: 2, toString: () => 'obj2' }; const obj3 = { key: 'obj3', value: 3, toString: () => 'obj3' }; const bst = new BinarySearchTree(nodeValueCompareFunction); bst.insert(obj2); bst.insert(obj3); bst.insert(obj1); expect(bst.toString()).toBe('obj1,obj2,obj3'); }); it('should be traversed to sorted array', () => { const bst = new BinarySearchTree(); bst.insert(10); bst.insert(-10); bst.insert(20); bst.insert(-20); bst.insert(25); bst.insert(6); expect(bst.toString()).toBe('-20,-10,6,10,20,25'); expect(bst.root.height).toBe(2); bst.insert(4); expect(bst.toString()).toBe('-20,-10,4,6,10,20,25'); expect(bst.root.height).toBe(3); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/tree/red-black-tree/RedBlackTree.js
src/data-structures/tree/red-black-tree/RedBlackTree.js
import BinarySearchTree from '../binary-search-tree/BinarySearchTree'; // Possible colors of red-black tree nodes. const RED_BLACK_TREE_COLORS = { red: 'red', black: 'black', }; // Color property name in meta information of the nodes. const COLOR_PROP_NAME = 'color'; export default class RedBlackTree extends BinarySearchTree { /** * @param {*} value * @return {BinarySearchTreeNode} */ insert(value) { const insertedNode = super.insert(value); // if (!this.root.left && !this.root.right) { if (this.nodeComparator.equal(insertedNode, this.root)) { // Make root to always be black. this.makeNodeBlack(insertedNode); } else { // Make all newly inserted nodes to be red. this.makeNodeRed(insertedNode); } // Check all conditions and balance the node. this.balance(insertedNode); return insertedNode; } /** * @param {*} value * @return {boolean} */ remove(value) { throw new Error(`Can't remove ${value}. Remove method is not implemented yet`); } /** * @param {BinarySearchTreeNode} node */ balance(node) { // If it is a root node then nothing to balance here. if (this.nodeComparator.equal(node, this.root)) { return; } // If the parent is black then done. Nothing to balance here. if (this.isNodeBlack(node.parent)) { return; } const grandParent = node.parent.parent; if (node.uncle && this.isNodeRed(node.uncle)) { // If node has red uncle then we need to do RECOLORING. // Recolor parent and uncle to black. this.makeNodeBlack(node.uncle); this.makeNodeBlack(node.parent); if (!this.nodeComparator.equal(grandParent, this.root)) { // Recolor grand-parent to red if it is not root. this.makeNodeRed(grandParent); } else { // If grand-parent is black root don't do anything. // Since root already has two black sibling that we've just recolored. return; } // Now do further checking for recolored grand-parent. this.balance(grandParent); } else if (!node.uncle || this.isNodeBlack(node.uncle)) { // If node uncle is black or absent then we need to do ROTATIONS. if (grandParent) { // Grand parent that we will receive after rotations. let newGrandParent; if (this.nodeComparator.equal(grandParent.left, node.parent)) { // Left case. if (this.nodeComparator.equal(node.parent.left, node)) { // Left-left case. newGrandParent = this.leftLeftRotation(grandParent); } else { // Left-right case. newGrandParent = this.leftRightRotation(grandParent); } } else { // Right case. if (this.nodeComparator.equal(node.parent.right, node)) { // Right-right case. newGrandParent = this.rightRightRotation(grandParent); } else { // Right-left case. newGrandParent = this.rightLeftRotation(grandParent); } } // Set newGrandParent as a root if it doesn't have parent. if (newGrandParent && newGrandParent.parent === null) { this.root = newGrandParent; // Recolor root into black. this.makeNodeBlack(this.root); } // Check if new grand parent don't violate red-black-tree rules. this.balance(newGrandParent); } } } /** * Left Left Case (p is left child of g and x is left child of p) * @param {BinarySearchTreeNode|BinaryTreeNode} grandParentNode * @return {BinarySearchTreeNode} */ leftLeftRotation(grandParentNode) { // Memorize the parent of grand-parent node. const grandGrandParent = grandParentNode.parent; // Check what type of sibling is our grandParentNode is (left or right). let grandParentNodeIsLeft; if (grandGrandParent) { grandParentNodeIsLeft = this.nodeComparator.equal(grandGrandParent.left, grandParentNode); } // Memorize grandParentNode's left node. const parentNode = grandParentNode.left; // Memorize parent's right node since we're going to transfer it to // grand parent's left subtree. const parentRightNode = parentNode.right; // Make grandParentNode to be right child of parentNode. parentNode.setRight(grandParentNode); // Move child's right subtree to grandParentNode's left subtree. grandParentNode.setLeft(parentRightNode); // Put parentNode node in place of grandParentNode. if (grandGrandParent) { if (grandParentNodeIsLeft) { grandGrandParent.setLeft(parentNode); } else { grandGrandParent.setRight(parentNode); } } else { // Make parent node a root parentNode.parent = null; } // Swap colors of grandParentNode and parentNode. this.swapNodeColors(parentNode, grandParentNode); // Return new root node. return parentNode; } /** * Left Right Case (p is left child of g and x is right child of p) * @param {BinarySearchTreeNode|BinaryTreeNode} grandParentNode * @return {BinarySearchTreeNode} */ leftRightRotation(grandParentNode) { // Memorize left and left-right nodes. const parentNode = grandParentNode.left; const childNode = parentNode.right; // We need to memorize child left node to prevent losing // left child subtree. Later it will be re-assigned to // parent's right sub-tree. const childLeftNode = childNode.left; // Make parentNode to be a left child of childNode node. childNode.setLeft(parentNode); // Move child's left subtree to parent's right subtree. parentNode.setRight(childLeftNode); // Put left-right node in place of left node. grandParentNode.setLeft(childNode); // Now we're ready to do left-left rotation. return this.leftLeftRotation(grandParentNode); } /** * Right Right Case (p is right child of g and x is right child of p) * @param {BinarySearchTreeNode|BinaryTreeNode} grandParentNode * @return {BinarySearchTreeNode} */ rightRightRotation(grandParentNode) { // Memorize the parent of grand-parent node. const grandGrandParent = grandParentNode.parent; // Check what type of sibling is our grandParentNode is (left or right). let grandParentNodeIsLeft; if (grandGrandParent) { grandParentNodeIsLeft = this.nodeComparator.equal(grandGrandParent.left, grandParentNode); } // Memorize grandParentNode's right node. const parentNode = grandParentNode.right; // Memorize parent's left node since we're going to transfer it to // grand parent's right subtree. const parentLeftNode = parentNode.left; // Make grandParentNode to be left child of parentNode. parentNode.setLeft(grandParentNode); // Transfer all left nodes from parent to right sub-tree of grandparent. grandParentNode.setRight(parentLeftNode); // Put parentNode node in place of grandParentNode. if (grandGrandParent) { if (grandParentNodeIsLeft) { grandGrandParent.setLeft(parentNode); } else { grandGrandParent.setRight(parentNode); } } else { // Make parent node a root. parentNode.parent = null; } // Swap colors of granParent and parent nodes. this.swapNodeColors(parentNode, grandParentNode); // Return new root node. return parentNode; } /** * Right Left Case (p is right child of g and x is left child of p) * @param {BinarySearchTreeNode|BinaryTreeNode} grandParentNode * @return {BinarySearchTreeNode} */ rightLeftRotation(grandParentNode) { // Memorize right and right-left nodes. const parentNode = grandParentNode.right; const childNode = parentNode.left; // We need to memorize child right node to prevent losing // right child subtree. Later it will be re-assigned to // parent's left sub-tree. const childRightNode = childNode.right; // Make parentNode to be a right child of childNode. childNode.setRight(parentNode); // Move child's right subtree to parent's left subtree. parentNode.setLeft(childRightNode); // Put childNode node in place of parentNode. grandParentNode.setRight(childNode); // Now we're ready to do right-right rotation. return this.rightRightRotation(grandParentNode); } /** * @param {BinarySearchTreeNode|BinaryTreeNode} node * @return {BinarySearchTreeNode} */ makeNodeRed(node) { node.meta.set(COLOR_PROP_NAME, RED_BLACK_TREE_COLORS.red); return node; } /** * @param {BinarySearchTreeNode|BinaryTreeNode} node * @return {BinarySearchTreeNode} */ makeNodeBlack(node) { node.meta.set(COLOR_PROP_NAME, RED_BLACK_TREE_COLORS.black); return node; } /** * @param {BinarySearchTreeNode|BinaryTreeNode} node * @return {boolean} */ isNodeRed(node) { return node.meta.get(COLOR_PROP_NAME) === RED_BLACK_TREE_COLORS.red; } /** * @param {BinarySearchTreeNode|BinaryTreeNode} node * @return {boolean} */ isNodeBlack(node) { return node.meta.get(COLOR_PROP_NAME) === RED_BLACK_TREE_COLORS.black; } /** * @param {BinarySearchTreeNode|BinaryTreeNode} node * @return {boolean} */ isNodeColored(node) { return this.isNodeRed(node) || this.isNodeBlack(node); } /** * @param {BinarySearchTreeNode|BinaryTreeNode} firstNode * @param {BinarySearchTreeNode|BinaryTreeNode} secondNode */ swapNodeColors(firstNode, secondNode) { const firstColor = firstNode.meta.get(COLOR_PROP_NAME); const secondColor = secondNode.meta.get(COLOR_PROP_NAME); firstNode.meta.set(COLOR_PROP_NAME, secondColor); secondNode.meta.set(COLOR_PROP_NAME, firstColor); } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/tree/red-black-tree/__test__/RedBlackTree.test.js
src/data-structures/tree/red-black-tree/__test__/RedBlackTree.test.js
import RedBlackTree from '../RedBlackTree'; describe('RedBlackTree', () => { it('should always color first inserted node as black', () => { const tree = new RedBlackTree(); const firstInsertedNode = tree.insert(10); expect(tree.isNodeColored(firstInsertedNode)).toBe(true); expect(tree.isNodeBlack(firstInsertedNode)).toBe(true); expect(tree.isNodeRed(firstInsertedNode)).toBe(false); expect(tree.toString()).toBe('10'); expect(tree.root.height).toBe(0); }); it('should always color new leaf node as red', () => { const tree = new RedBlackTree(); const firstInsertedNode = tree.insert(10); const secondInsertedNode = tree.insert(15); const thirdInsertedNode = tree.insert(5); expect(tree.isNodeBlack(firstInsertedNode)).toBe(true); expect(tree.isNodeRed(secondInsertedNode)).toBe(true); expect(tree.isNodeRed(thirdInsertedNode)).toBe(true); expect(tree.toString()).toBe('5,10,15'); expect(tree.root.height).toBe(1); }); it('should balance itself', () => { const tree = new RedBlackTree(); tree.insert(5); tree.insert(10); tree.insert(15); tree.insert(20); tree.insert(25); tree.insert(30); expect(tree.toString()).toBe('5,10,15,20,25,30'); expect(tree.root.height).toBe(3); }); it('should balance itself when parent is black', () => { const tree = new RedBlackTree(); const node1 = tree.insert(10); expect(tree.isNodeBlack(node1)).toBe(true); const node2 = tree.insert(-10); expect(tree.isNodeBlack(node1)).toBe(true); expect(tree.isNodeRed(node2)).toBe(true); const node3 = tree.insert(20); expect(tree.isNodeBlack(node1)).toBe(true); expect(tree.isNodeRed(node2)).toBe(true); expect(tree.isNodeRed(node3)).toBe(true); const node4 = tree.insert(-20); expect(tree.isNodeBlack(node1)).toBe(true); expect(tree.isNodeBlack(node2)).toBe(true); expect(tree.isNodeBlack(node3)).toBe(true); expect(tree.isNodeRed(node4)).toBe(true); const node5 = tree.insert(25); expect(tree.isNodeBlack(node1)).toBe(true); expect(tree.isNodeBlack(node2)).toBe(true); expect(tree.isNodeBlack(node3)).toBe(true); expect(tree.isNodeRed(node4)).toBe(true); expect(tree.isNodeRed(node5)).toBe(true); const node6 = tree.insert(6); expect(tree.isNodeBlack(node1)).toBe(true); expect(tree.isNodeBlack(node2)).toBe(true); expect(tree.isNodeBlack(node3)).toBe(true); expect(tree.isNodeRed(node4)).toBe(true); expect(tree.isNodeRed(node5)).toBe(true); expect(tree.isNodeRed(node6)).toBe(true); expect(tree.toString()).toBe('-20,-10,6,10,20,25'); expect(tree.root.height).toBe(2); const node7 = tree.insert(4); expect(tree.root.left.value).toEqual(node2.value); expect(tree.toString()).toBe('-20,-10,4,6,10,20,25'); expect(tree.root.height).toBe(3); expect(tree.isNodeBlack(node1)).toBe(true); expect(tree.isNodeRed(node2)).toBe(true); expect(tree.isNodeBlack(node3)).toBe(true); expect(tree.isNodeBlack(node4)).toBe(true); expect(tree.isNodeBlack(node4)).toBe(true); expect(tree.isNodeRed(node5)).toBe(true); expect(tree.isNodeBlack(node6)).toBe(true); expect(tree.isNodeRed(node7)).toBe(true); }); it('should balance itself when uncle is red', () => { const tree = new RedBlackTree(); const node1 = tree.insert(10); const node2 = tree.insert(-10); const node3 = tree.insert(20); const node4 = tree.insert(-20); const node5 = tree.insert(6); const node6 = tree.insert(15); const node7 = tree.insert(25); const node8 = tree.insert(2); const node9 = tree.insert(8); expect(tree.toString()).toBe('-20,-10,2,6,8,10,15,20,25'); expect(tree.root.height).toBe(3); expect(tree.isNodeBlack(node1)).toBe(true); expect(tree.isNodeRed(node2)).toBe(true); expect(tree.isNodeBlack(node3)).toBe(true); expect(tree.isNodeBlack(node4)).toBe(true); expect(tree.isNodeBlack(node5)).toBe(true); expect(tree.isNodeRed(node6)).toBe(true); expect(tree.isNodeRed(node7)).toBe(true); expect(tree.isNodeRed(node8)).toBe(true); expect(tree.isNodeRed(node9)).toBe(true); const node10 = tree.insert(4); expect(tree.toString()).toBe('-20,-10,2,4,6,8,10,15,20,25'); expect(tree.root.height).toBe(3); expect(tree.root.value).toBe(node5.value); expect(tree.isNodeBlack(node5)).toBe(true); expect(tree.isNodeRed(node1)).toBe(true); expect(tree.isNodeRed(node2)).toBe(true); expect(tree.isNodeRed(node10)).toBe(true); expect(tree.isNodeRed(node6)).toBe(true); expect(tree.isNodeRed(node7)).toBe(true); expect(tree.isNodeBlack(node4)).toBe(true); expect(tree.isNodeBlack(node8)).toBe(true); expect(tree.isNodeBlack(node9)).toBe(true); expect(tree.isNodeBlack(node3)).toBe(true); }); it('should do left-left rotation', () => { const tree = new RedBlackTree(); const node1 = tree.insert(10); const node2 = tree.insert(-10); const node3 = tree.insert(20); const node4 = tree.insert(7); const node5 = tree.insert(15); expect(tree.toString()).toBe('-10,7,10,15,20'); expect(tree.root.height).toBe(2); expect(tree.isNodeBlack(node1)).toBe(true); expect(tree.isNodeBlack(node2)).toBe(true); expect(tree.isNodeBlack(node3)).toBe(true); expect(tree.isNodeRed(node4)).toBe(true); expect(tree.isNodeRed(node5)).toBe(true); const node6 = tree.insert(13); expect(tree.toString()).toBe('-10,7,10,13,15,20'); expect(tree.root.height).toBe(2); expect(tree.isNodeBlack(node1)).toBe(true); expect(tree.isNodeBlack(node2)).toBe(true); expect(tree.isNodeBlack(node5)).toBe(true); expect(tree.isNodeRed(node4)).toBe(true); expect(tree.isNodeRed(node6)).toBe(true); expect(tree.isNodeRed(node3)).toBe(true); }); it('should do left-right rotation', () => { const tree = new RedBlackTree(); const node1 = tree.insert(10); const node2 = tree.insert(-10); const node3 = tree.insert(20); const node4 = tree.insert(7); const node5 = tree.insert(15); expect(tree.toString()).toBe('-10,7,10,15,20'); expect(tree.root.height).toBe(2); expect(tree.isNodeBlack(node1)).toBe(true); expect(tree.isNodeBlack(node2)).toBe(true); expect(tree.isNodeBlack(node3)).toBe(true); expect(tree.isNodeRed(node4)).toBe(true); expect(tree.isNodeRed(node5)).toBe(true); const node6 = tree.insert(17); expect(tree.toString()).toBe('-10,7,10,15,17,20'); expect(tree.root.height).toBe(2); expect(tree.isNodeBlack(node1)).toBe(true); expect(tree.isNodeBlack(node2)).toBe(true); expect(tree.isNodeBlack(node6)).toBe(true); expect(tree.isNodeRed(node4)).toBe(true); expect(tree.isNodeRed(node5)).toBe(true); expect(tree.isNodeRed(node3)).toBe(true); }); it('should do recoloring, left-left and left-right rotation', () => { const tree = new RedBlackTree(); const node1 = tree.insert(10); const node2 = tree.insert(-10); const node3 = tree.insert(20); const node4 = tree.insert(-20); const node5 = tree.insert(6); const node6 = tree.insert(15); const node7 = tree.insert(30); const node8 = tree.insert(1); const node9 = tree.insert(9); expect(tree.toString()).toBe('-20,-10,1,6,9,10,15,20,30'); expect(tree.root.height).toBe(3); expect(tree.isNodeBlack(node1)).toBe(true); expect(tree.isNodeRed(node2)).toBe(true); expect(tree.isNodeBlack(node3)).toBe(true); expect(tree.isNodeBlack(node4)).toBe(true); expect(tree.isNodeBlack(node5)).toBe(true); expect(tree.isNodeRed(node6)).toBe(true); expect(tree.isNodeRed(node7)).toBe(true); expect(tree.isNodeRed(node8)).toBe(true); expect(tree.isNodeRed(node9)).toBe(true); tree.insert(4); expect(tree.toString()).toBe('-20,-10,1,4,6,9,10,15,20,30'); expect(tree.root.height).toBe(3); }); it('should do right-left rotation', () => { const tree = new RedBlackTree(); const node1 = tree.insert(10); const node2 = tree.insert(-10); const node3 = tree.insert(20); const node4 = tree.insert(-20); const node5 = tree.insert(6); const node6 = tree.insert(30); expect(tree.toString()).toBe('-20,-10,6,10,20,30'); expect(tree.root.height).toBe(2); expect(tree.isNodeBlack(node1)).toBe(true); expect(tree.isNodeBlack(node2)).toBe(true); expect(tree.isNodeBlack(node3)).toBe(true); expect(tree.isNodeRed(node4)).toBe(true); expect(tree.isNodeRed(node5)).toBe(true); expect(tree.isNodeRed(node6)).toBe(true); const node7 = tree.insert(25); const rightNode = tree.root.right; const rightLeftNode = rightNode.left; const rightRightNode = rightNode.right; expect(rightNode.value).toBe(node7.value); expect(rightLeftNode.value).toBe(node3.value); expect(rightRightNode.value).toBe(node6.value); expect(tree.toString()).toBe('-20,-10,6,10,20,25,30'); expect(tree.root.height).toBe(2); expect(tree.isNodeBlack(node1)).toBe(true); expect(tree.isNodeBlack(node2)).toBe(true); expect(tree.isNodeBlack(node7)).toBe(true); expect(tree.isNodeRed(node4)).toBe(true); expect(tree.isNodeRed(node5)).toBe(true); expect(tree.isNodeRed(node3)).toBe(true); expect(tree.isNodeRed(node6)).toBe(true); }); it('should do left-left rotation with left grand-parent', () => { const tree = new RedBlackTree(); tree.insert(20); tree.insert(15); tree.insert(25); tree.insert(10); tree.insert(5); expect(tree.toString()).toBe('5,10,15,20,25'); expect(tree.root.height).toBe(2); }); it('should do right-right rotation with left grand-parent', () => { const tree = new RedBlackTree(); tree.insert(20); tree.insert(15); tree.insert(25); tree.insert(17); tree.insert(19); expect(tree.toString()).toBe('15,17,19,20,25'); expect(tree.root.height).toBe(2); }); it('should throw an error when trying to remove node', () => { const removeNodeFromRedBlackTree = () => { const tree = new RedBlackTree(); tree.remove(1); }; expect(removeNodeFromRedBlackTree).toThrowError(); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/tree/segment-tree/SegmentTree.js
src/data-structures/tree/segment-tree/SegmentTree.js
import isPowerOfTwo from '../../../algorithms/math/is-power-of-two/isPowerOfTwo'; export default class SegmentTree { /** * @param {number[]} inputArray * @param {function} operation - binary function (i.e. sum, min) * @param {number} operationFallback - operation fallback value (i.e. 0 for sum, Infinity for min) */ constructor(inputArray, operation, operationFallback) { this.inputArray = inputArray; this.operation = operation; this.operationFallback = operationFallback; // Init array representation of segment tree. this.segmentTree = this.initSegmentTree(this.inputArray); this.buildSegmentTree(); } /** * @param {number[]} inputArray * @return {number[]} */ initSegmentTree(inputArray) { let segmentTreeArrayLength; const inputArrayLength = inputArray.length; if (isPowerOfTwo(inputArrayLength)) { // If original array length is a power of two. segmentTreeArrayLength = (2 * inputArrayLength) - 1; } else { // If original array length is not a power of two then we need to find // next number that is a power of two and use it to calculate // tree array size. This is happens because we need to fill empty children // in perfect binary tree with nulls.And those nulls need extra space. const currentPower = Math.floor(Math.log2(inputArrayLength)); const nextPower = currentPower + 1; const nextPowerOfTwoNumber = 2 ** nextPower; segmentTreeArrayLength = (2 * nextPowerOfTwoNumber) - 1; } return new Array(segmentTreeArrayLength).fill(null); } /** * Build segment tree. */ buildSegmentTree() { const leftIndex = 0; const rightIndex = this.inputArray.length - 1; const position = 0; this.buildTreeRecursively(leftIndex, rightIndex, position); } /** * Build segment tree recursively. * * @param {number} leftInputIndex * @param {number} rightInputIndex * @param {number} position */ buildTreeRecursively(leftInputIndex, rightInputIndex, position) { // If low input index and high input index are equal that would mean // the we have finished splitting and we are already came to the leaf // of the segment tree. We need to copy this leaf value from input // array to segment tree. if (leftInputIndex === rightInputIndex) { this.segmentTree[position] = this.inputArray[leftInputIndex]; return; } // Split input array on two halves and process them recursively. const middleIndex = Math.floor((leftInputIndex + rightInputIndex) / 2); // Process left half of the input array. this.buildTreeRecursively(leftInputIndex, middleIndex, this.getLeftChildIndex(position)); // Process right half of the input array. this.buildTreeRecursively(middleIndex + 1, rightInputIndex, this.getRightChildIndex(position)); // Once every tree leaf is not empty we're able to build tree bottom up using // provided operation function. this.segmentTree[position] = this.operation( this.segmentTree[this.getLeftChildIndex(position)], this.segmentTree[this.getRightChildIndex(position)], ); } /** * Do range query on segment tree in context of this.operation function. * * @param {number} queryLeftIndex * @param {number} queryRightIndex * @return {number} */ rangeQuery(queryLeftIndex, queryRightIndex) { const leftIndex = 0; const rightIndex = this.inputArray.length - 1; const position = 0; return this.rangeQueryRecursive( queryLeftIndex, queryRightIndex, leftIndex, rightIndex, position, ); } /** * Do range query on segment tree recursively in context of this.operation function. * * @param {number} queryLeftIndex - left index of the query * @param {number} queryRightIndex - right index of the query * @param {number} leftIndex - left index of input array segment * @param {number} rightIndex - right index of input array segment * @param {number} position - root position in binary tree * @return {number} */ rangeQueryRecursive(queryLeftIndex, queryRightIndex, leftIndex, rightIndex, position) { if (queryLeftIndex <= leftIndex && queryRightIndex >= rightIndex) { // Total overlap. return this.segmentTree[position]; } if (queryLeftIndex > rightIndex || queryRightIndex < leftIndex) { // No overlap. return this.operationFallback; } // Partial overlap. const middleIndex = Math.floor((leftIndex + rightIndex) / 2); const leftOperationResult = this.rangeQueryRecursive( queryLeftIndex, queryRightIndex, leftIndex, middleIndex, this.getLeftChildIndex(position), ); const rightOperationResult = this.rangeQueryRecursive( queryLeftIndex, queryRightIndex, middleIndex + 1, rightIndex, this.getRightChildIndex(position), ); return this.operation(leftOperationResult, rightOperationResult); } /** * Left child index. * @param {number} parentIndex * @return {number} */ getLeftChildIndex(parentIndex) { return (2 * parentIndex) + 1; } /** * Right child index. * @param {number} parentIndex * @return {number} */ getRightChildIndex(parentIndex) { return (2 * parentIndex) + 2; } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/data-structures/tree/segment-tree/__test__/SegmentTree.test.js
src/data-structures/tree/segment-tree/__test__/SegmentTree.test.js
import SegmentTree from '../SegmentTree'; describe('SegmentTree', () => { it('should build tree for input array #0 with length of power of two', () => { const array = [-1, 2]; const segmentTree = new SegmentTree(array, Math.min, Infinity); expect(segmentTree.segmentTree).toEqual([-1, -1, 2]); expect(segmentTree.segmentTree.length).toBe((2 * array.length) - 1); }); it('should build tree for input array #1 with length of power of two', () => { const array = [-1, 2, 4, 0]; const segmentTree = new SegmentTree(array, Math.min, Infinity); expect(segmentTree.segmentTree).toEqual([-1, -1, 0, -1, 2, 4, 0]); expect(segmentTree.segmentTree.length).toBe((2 * array.length) - 1); }); it('should build tree for input array #0 with length not of power of two', () => { const array = [0, 1, 2]; const segmentTree = new SegmentTree(array, Math.min, Infinity); expect(segmentTree.segmentTree).toEqual([0, 0, 2, 0, 1, null, null]); expect(segmentTree.segmentTree.length).toBe((2 * 4) - 1); }); it('should build tree for input array #1 with length not of power of two', () => { const array = [-1, 3, 4, 0, 2, 1]; const segmentTree = new SegmentTree(array, Math.min, Infinity); expect(segmentTree.segmentTree).toEqual([ -1, -1, 0, -1, 4, 0, 1, -1, 3, null, null, 0, 2, null, null, ]); expect(segmentTree.segmentTree.length).toBe((2 * 8) - 1); }); it('should build max array', () => { const array = [-1, 2, 4, 0]; const segmentTree = new SegmentTree(array, Math.max, -Infinity); expect(segmentTree.segmentTree).toEqual([4, 2, 4, -1, 2, 4, 0]); expect(segmentTree.segmentTree.length).toBe((2 * array.length) - 1); }); it('should build sum array', () => { const array = [-1, 2, 4, 0]; const segmentTree = new SegmentTree(array, (a, b) => (a + b), 0); expect(segmentTree.segmentTree).toEqual([5, 1, 4, -1, 2, 4, 0]); expect(segmentTree.segmentTree.length).toBe((2 * array.length) - 1); }); it('should do min range query on power of two length array', () => { const array = [-1, 3, 4, 0, 2, 1]; const segmentTree = new SegmentTree(array, Math.min, Infinity); expect(segmentTree.rangeQuery(0, 5)).toBe(-1); expect(segmentTree.rangeQuery(0, 2)).toBe(-1); expect(segmentTree.rangeQuery(1, 3)).toBe(0); expect(segmentTree.rangeQuery(2, 4)).toBe(0); expect(segmentTree.rangeQuery(4, 5)).toBe(1); expect(segmentTree.rangeQuery(2, 2)).toBe(4); }); it('should do min range query on not power of two length array', () => { const array = [-1, 2, 4, 0]; const segmentTree = new SegmentTree(array, Math.min, Infinity); expect(segmentTree.rangeQuery(0, 4)).toBe(-1); expect(segmentTree.rangeQuery(0, 1)).toBe(-1); expect(segmentTree.rangeQuery(1, 3)).toBe(0); expect(segmentTree.rangeQuery(1, 2)).toBe(2); expect(segmentTree.rangeQuery(2, 3)).toBe(0); expect(segmentTree.rangeQuery(2, 2)).toBe(4); }); it('should do max range query', () => { const array = [-1, 3, 4, 0, 2, 1]; const segmentTree = new SegmentTree(array, Math.max, -Infinity); expect(segmentTree.rangeQuery(0, 5)).toBe(4); expect(segmentTree.rangeQuery(0, 1)).toBe(3); expect(segmentTree.rangeQuery(1, 3)).toBe(4); expect(segmentTree.rangeQuery(2, 4)).toBe(4); expect(segmentTree.rangeQuery(4, 5)).toBe(2); expect(segmentTree.rangeQuery(3, 3)).toBe(0); }); it('should do sum range query', () => { const array = [-1, 3, 4, 0, 2, 1]; const segmentTree = new SegmentTree(array, (a, b) => (a + b), 0); expect(segmentTree.rangeQuery(0, 5)).toBe(9); expect(segmentTree.rangeQuery(0, 1)).toBe(2); expect(segmentTree.rangeQuery(1, 3)).toBe(7); expect(segmentTree.rangeQuery(2, 4)).toBe(6); expect(segmentTree.rangeQuery(4, 5)).toBe(3); expect(segmentTree.rangeQuery(3, 3)).toBe(0); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/utils/comparator/Comparator.js
src/utils/comparator/Comparator.js
export default class Comparator { /** * Constructor. * @param {function(a: *, b: *)} [compareFunction] - It may be custom compare function that, let's * say may compare custom objects together. */ constructor(compareFunction) { this.compare = compareFunction || Comparator.defaultCompareFunction; } /** * Default comparison function. It just assumes that "a" and "b" are strings or numbers. * @param {(string|number)} a * @param {(string|number)} b * @returns {number} */ static defaultCompareFunction(a, b) { if (a === b) { return 0; } return a < b ? -1 : 1; } /** * Checks if two variables are equal. * @param {*} a * @param {*} b * @return {boolean} */ equal(a, b) { return this.compare(a, b) === 0; } /** * Checks if variable "a" is less than "b". * @param {*} a * @param {*} b * @return {boolean} */ lessThan(a, b) { return this.compare(a, b) < 0; } /** * Checks if variable "a" is greater than "b". * @param {*} a * @param {*} b * @return {boolean} */ greaterThan(a, b) { return this.compare(a, b) > 0; } /** * Checks if variable "a" is less than or equal to "b". * @param {*} a * @param {*} b * @return {boolean} */ lessThanOrEqual(a, b) { return this.lessThan(a, b) || this.equal(a, b); } /** * Checks if variable "a" is greater than or equal to "b". * @param {*} a * @param {*} b * @return {boolean} */ greaterThanOrEqual(a, b) { return this.greaterThan(a, b) || this.equal(a, b); } /** * Reverses the comparison order. */ reverse() { const compareOriginal = this.compare; this.compare = (a, b) => compareOriginal(b, a); } }
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/utils/comparator/__test__/Comparator.test.js
src/utils/comparator/__test__/Comparator.test.js
import Comparator from '../Comparator'; describe('Comparator', () => { it('should compare with default comparator function', () => { const comparator = new Comparator(); expect(comparator.equal(0, 0)).toBe(true); expect(comparator.equal(0, 1)).toBe(false); expect(comparator.equal('a', 'a')).toBe(true); expect(comparator.lessThan(1, 2)).toBe(true); expect(comparator.lessThan(-1, 2)).toBe(true); expect(comparator.lessThan('a', 'b')).toBe(true); expect(comparator.lessThan('a', 'ab')).toBe(true); expect(comparator.lessThan(10, 2)).toBe(false); expect(comparator.lessThanOrEqual(10, 2)).toBe(false); expect(comparator.lessThanOrEqual(1, 1)).toBe(true); expect(comparator.lessThanOrEqual(0, 0)).toBe(true); expect(comparator.greaterThan(0, 0)).toBe(false); expect(comparator.greaterThan(10, 0)).toBe(true); expect(comparator.greaterThanOrEqual(10, 0)).toBe(true); expect(comparator.greaterThanOrEqual(10, 10)).toBe(true); expect(comparator.greaterThanOrEqual(0, 10)).toBe(false); }); it('should compare with custom comparator function', () => { const comparator = new Comparator((a, b) => { if (a.length === b.length) { return 0; } return a.length < b.length ? -1 : 1; }); expect(comparator.equal('a', 'b')).toBe(true); expect(comparator.equal('a', '')).toBe(false); expect(comparator.lessThan('b', 'aa')).toBe(true); expect(comparator.greaterThanOrEqual('a', 'aa')).toBe(false); expect(comparator.greaterThanOrEqual('aa', 'a')).toBe(true); expect(comparator.greaterThanOrEqual('a', 'a')).toBe(true); comparator.reverse(); expect(comparator.equal('a', 'b')).toBe(true); expect(comparator.equal('a', '')).toBe(false); expect(comparator.lessThan('b', 'aa')).toBe(false); expect(comparator.greaterThanOrEqual('a', 'aa')).toBe(true); expect(comparator.greaterThanOrEqual('aa', 'a')).toBe(false); expect(comparator.greaterThanOrEqual('a', 'a')).toBe(true); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/playground/playground.js
src/playground/playground.js
// Import any algorithmic dependencies you need for your playground code here. import factorial from '../algorithms/math/factorial/factorial'; // Write your playground code inside the playground() function. // Test your code from __tests__/playground.test.js // Launch playground tests by running: npm test -- 'playground' function playground() { // Replace the next line with your playground code. return factorial(5); } export default playground;
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
trekhleb/javascript-algorithms
https://github.com/trekhleb/javascript-algorithms/blob/1503325329d63f7fead7f455fda5a4338b4e93bb/src/playground/__test__/playground.test.js
src/playground/__test__/playground.test.js
import playground from '../playground'; describe('playground', () => { it('should return correct results', () => { // Replace the next dummy test with your playground function tests. expect(playground()).toBe(120); }); });
javascript
MIT
1503325329d63f7fead7f455fda5a4338b4e93bb
2026-01-04T14:56:49.187241Z
false
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/chrome/backgroundscript.js
src/chrome/backgroundscript.js
/* * Copyright Adam Pritchard 2016 * MIT License : https://adampritchard.mit-license.org/ */ "use strict"; /*global chrome:false, OptionsStore:false, MarkdownRender:false, marked:false, hljs:false, Utils:false, CommonLogic:false, ContentPermissions:false */ /*jshint devel:true, browser:true*/ if (typeof browser === "undefined") { // Chrome does not support the browser namespace yet. // See https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/background globalThis.browser = chrome; } // We supply a #hash to the background page, so that we know when we're // loaded via `background.page` (manifest V2 and Firefox manifest V3) vs // `background.service_worker` (manifest V3 in Chrome). var backgroundPage = !!location.hash; if (!backgroundPage) { // When loaded via a background page, the support scripts are already // present. When loaded via a service worker, we need to import them. // (`importScripts` is only available in service workers.) importScripts('../common/vendor/dompurify.min.js'); importScripts('../common/utils.js'); importScripts('../common/common-logic.js'); importScripts('../common/marked.js'); importScripts('../common/highlightjs/highlight.js'); importScripts('../common/markdown-render.js'); importScripts('../common/options-store.js'); importScripts('../common/content-permissions.js'); } // Note that this file is both the script for a background page _and_ for a service // worker. The way these things work are quite different, and we must be cognizant of that // while writing this file. // // The key difference is that a background page is loaded once per browser session; a // service worker is loaded when extension-related events occur, and then is torn down // after 30 seconds of inactivity (with lifecycle caveats). This means that we can't rely // on global variables to store state, and we must be mindful about how we handle // messages. // For the background page, this listener is added once and remains active for the browser // session; for the service worker, this listener is added every time the service worker // is loaded, and is torn down when the service worker is torn down. chrome.runtime.onInstalled.addListener((details) => { if (details.reason !== 'install' && details.reason !== 'update') { return; } // Create the context menu that will signal our main code. // This must be called only once, when installed or updated, so we do it here. chrome.contextMenus.create({ id: 'markdown-here-context-menu', contexts: ['editable'], title: Utils.getMessage('context_menu_item') }); // Note: If we find that the upgrade info page opens too often, we may // need to add delays. See: https://github.com/adam-p/markdown-here/issues/119 upgradeCheck(); }); function upgradeCheck() { OptionsStore.get(function(options) { var appManifest = chrome.runtime.getManifest(); var optionsURL = '/common/options.html'; if (typeof(options['last-version']) === 'undefined') { // Update our last version. Only when the update is complete will we take // the next action, to make sure it doesn't happen every time we start up. OptionsStore.set({ 'last-version': appManifest.version }, function() { // This is the very first time the extensions has been run, so show the // options page. chrome.tabs.create({ url: Utils.getLocalURL(optionsURL) }); }); } else if (options['last-version'] !== appManifest.version) { // Update our last version. Only when the update is complete will we take // the next action, to make sure it doesn't happen every time we start up. OptionsStore.set({ 'last-version': appManifest.version }, function() { // The extension has been newly updated chrome.action.setPopup({ popup: Utils.getLocalURL('/chrome/upgrade-notification-popup.html') }, function() { try { chrome.action.openPopup(); } catch (e) { // Firefox won't allow us to open a popup programmatically (i.e., in the absence of a user gesture) console.error('Failed to open upgrade notification popup:', e); } }); }); } }); } // Handle context menu clicks. chrome.contextMenus.onClicked.addListener(async function(info, tab) { await handleActionClick(tab, info); }); // Handle rendering requests from the content script. Note that incoming messages will // revive the service worker, then process the message, then tear down the service worker. // See the comment in markdown-render.js for why we use these requests. chrome.runtime.onMessage.addListener(function(request, sender, responseCallback) { // The content script can load in a not-real tab (like the search box), which // has an invalid `sender.tab` value. We should just ignore these pages. if (typeof(sender.tab) === 'undefined' || typeof(sender.tab.id) === 'undefined' || sender.tab.id < 0) { return false; } if (request.action === 'render') { OptionsStore.get(function(prefs) { responseCallback({ html: MarkdownRender.markdownRender( request.mdText, prefs, marked, hljs), css: (prefs['main-css'] + prefs['syntax-css']) }); }); return true; } else if (request.action === 'get-options') { OptionsStore.get(function(prefs) { responseCallback(prefs); }); return true; } else if (request.action === 'get-forgot-to-render-prompt') { CommonLogic.getForgotToRenderPromptContent(function(html) { responseCallback({html: html}); }); return true; } else if (request.action === 'open-tab') { chrome.tabs.create({ 'url': request.url }); return false; } else if (request.action === 'test-request') { responseCallback('test-request-good'); return false; } else { throw 'unmatched request action: ' + request.action; } }); // Add the browserAction (the button in the browser toolbar) listener. // This also handles the _execute_action keyboard command automatically. chrome.action.onClicked.addListener(async function(tab) { await handleActionClick(tab); }); chrome.tabs.onUpdated.addListener(async function(tabId, changeInfo, tab) { // Only proceed when the tab has finished loading and has a valid URL if (changeInfo.status === 'complete' && tab.url) { // Auto-inject scripts for domains where we already have permission. // This allows us to run _before_ the user clicks the button, enabling features // such as the "forgot to render" prompt. try { if (await ContentPermissions.hasPermission(tab.url)) { await Injector.injectScripts(tabId); } } catch (e) { // Invalid URL or other error -- just skip } } }); // Handle a click on the action button or context menu item async function handleActionClick(tab, info = undefined) { // Check if the current tab is the options page const optionsPageUrl = Utils.getLocalURL('/common/options.html'); if (tab.url && tab.url.startsWith(optionsPageUrl)) { // For the options page, send a runtime message directly without injection // (because injection won't work on the options page). chrome.tabs.sendMessage(tab.id, { action: 'button-click', info: info }); return true; } // For all other pages, proceed with the normal injection flow const injected = await Injector.injectScripts(tab.id); if (!injected) { console.error('Failed to inject scripts'); return false; } // Send the toggle message chrome.tabs.sendMessage(tab.id, { action: 'button-click', info: info }); return true; } const Injector = { // Scripts to inject in order CONTENT_SCRIPTS: [ '/common/vendor/dompurify.min.js', '/common/utils.js', '/common/common-logic.js', '/common/jsHtmlToText.js', '/common/marked.js', '/common/mdh-html-to-text.js', '/common/markdown-here.js', '/chrome/contentscript.js' ], // Check if scripts are already injected in a tab and mark that they are. we do these // in one step to minimize the potential for race conditions, where there's an attempt // to inject the scripts multiple times. async checkAndMarkInjected(tabId) { try { const results = await chrome.scripting.executeScript({ target: { tabId: tabId }, func: () => {const alreadyInjected = window.markdownHereInjected; window.markdownHereInjected = true; return !!alreadyInjected;} }); return results && results[0] && results[0].result === true; } catch (e) { // Tab might not be accessible return false; } }, // Inject content scripts into a tab async injectScripts(tabId) { try { // Check if already injected if (await this.checkAndMarkInjected(tabId)) { return true; } // Inject files in order for (const script of this.CONTENT_SCRIPTS) { await chrome.scripting.executeScript({ target: { tabId: tabId }, files: [script] }); } return true; } catch (e) { // Note that we're not cleaning up our "injected" flag, nor any of the scripts that // might have been injected before the error occurred. An error shouldn't occur, // and we'll just give up on working in this tab if it does. console.error('Error injecting scripts:', e); return false; } } };
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
false
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/chrome/upgrade-notification-popup.js
src/chrome/upgrade-notification-popup.js
/* * Copyright Adam Pritchard 2025 * MIT License : https://adampritchard.mit-license.org/ */ "use strict"; /*global chrome:false, OptionsStore:false, Utils:false */ /* * Handles the upgrade notification popup behavior */ function onLoad() { // Get the previous version from storage using OptionsStore OptionsStore.get(function(options) { const prevVersion = options['last-version'] || ''; // Get localized messages const upgradeText = Utils.getMessage('upgrade_notification_text'); const changesTitle = Utils.getMessage('upgrade_notification_changes_tooltip'); const dismissTitle = Utils.getMessage('upgrade_notification_dismiss_tooltip'); // Update text content document.getElementById('upgrade-notification-text').textContent = upgradeText; document.getElementById('upgrade-notification-link').title = changesTitle; document.getElementById('upgrade-notification-close').title = dismissTitle; // Handle link click - open options page with previous version document.getElementById('upgrade-notification-link').addEventListener('click', function(e) { e.preventDefault(); const optionsUrl = Utils.getLocalURL('/common/options.html'); const urlWithParam = optionsUrl + '?prevVer=' + encodeURIComponent(prevVersion); // Open options page in new tab chrome.tabs.create({ url: urlWithParam }, function() { // Clear the popup and restore normal action behavior clearUpgradeNotification(); }); }); // Handle close button click document.getElementById('upgrade-notification-close').addEventListener('click', function(e) { e.preventDefault(); clearUpgradeNotification(); }); }); } document.addEventListener('DOMContentLoaded', onLoad, false); function clearUpgradeNotification() { // Clear the popup setting to restore normal click behavior chrome.action.setPopup({ popup: '' }, function() { // Close the popup window.close(); }); }
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
false
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/chrome/contentscript.js
src/chrome/contentscript.js
/* * Copyright Adam Pritchard 2013 * MIT License : https://adampritchard.mit-license.org/ */ "use strict"; /*global chrome:false, markdownHere:false, CommonLogic:false, htmlToText:false, Utils:false, MdhHtmlToText:false, marked:false*/ /*jshint devel:true, browser:true*/ /* * Chrome-specific code for responding to the context menu item and providing * rendering services. * * This version removes automatic injection and focus detection. * Scripts are now injected on-demand when the user activates the extension. */ // Handle the menu-item click function requestHandler(request, sender, sendResponse) { if (request && request.action === 'button-click') { // Check if the focused element is a valid render target const focusedElem = markdownHere.findFocusedElem(window.document); if (!focusedElem) { // Shouldn't happen. But if it does, just silently abort. return false; } if (!markdownHere.elementCanBeRendered(focusedElem)) { alert(Utils.getMessage('invalid_field')); return false; } const logger = function() { console.log.apply(console, arguments); }; const mdReturn = markdownHere( document, requestMarkdownConversion, logger, markdownRenderComplete); if (typeof(mdReturn) === 'string') { // Error message was returned. alert(mdReturn); return false; } } } chrome.runtime.onMessage.addListener(requestHandler); // The rendering service provided to the content script. // See the comment in markdown-render.js for why we do this. function requestMarkdownConversion(elem, range, callback) { var mdhHtmlToText = new MdhHtmlToText.MdhHtmlToText(elem, range); // Send a request to the add-on script to actually do the rendering. Utils.makeRequestToPrivilegedScript( document, { action: 'render', mdText: mdhHtmlToText.get() }, function(response) { var renderedMarkdown = mdhHtmlToText.postprocess(response.html); callback(renderedMarkdown, response.css); }); } // When rendering (or unrendering) completed function markdownRenderComplete(elem, rendered) { // No-op for now } /* * Forgot-to-render check * Sets up hooks on send buttons to check for unrendered Markdown */ let forgotToRenderIntervalCheckPrefs = null; // Get the options for the forgot-to-render check Utils.makeRequestToPrivilegedScript( document, { action: 'get-options' }, function(prefs) { forgotToRenderIntervalCheckPrefs = prefs; }); // Check periodically if we should set up forgot-to-render hooks function forgotToRenderCheck() { if (!forgotToRenderIntervalCheckPrefs || !forgotToRenderIntervalCheckPrefs['forgot-to-render-check-enabled-2']) { return; } let focusedElem = markdownHere.findFocusedElem(window.document); if (!focusedElem) { return; } CommonLogic.forgotToRenderIntervalCheck( focusedElem, markdownHere, MdhHtmlToText, marked, forgotToRenderIntervalCheckPrefs); } // Run the check every 2 seconds to catch dynamically loaded elements setInterval(forgotToRenderCheck, 2000);
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
false
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/common/common-logic.js
src/common/common-logic.js
/* * Copyright Adam Pritchard 2013 * MIT License : https://adampritchard.mit-license.org/ */ /* * Application logic that is common to all (or some) platforms. * (And isn't generic enough for utils.js or render-y enough for markdown-render.js, * etc.) * * This module assumes that a global `window` is available. */ ;(function() { "use strict"; /*global module:false, chrome:false, Utils:false*/ var DEBUG = false; function debugLog() { var i, log = ''; if (!DEBUG) { return; } for (i = 0; i < arguments.length; i++) { log += String(arguments[i]) + ' // '; } Utils.consoleLog(log); } /* ****************************************************************************** Forgot-to-render check ****************************************************************************** */ /* * Gets the forgot-to-render prompt. This must be called from a privileged script. */ function getForgotToRenderPromptContent(responseCallback) { debugLog('getForgotToRenderPromptContent', 'getting'); Utils.getLocalFile( Utils.getLocalURL('/common/forgot-to-render-prompt.html'), 'text', function(html) { html = html.replace('{{forgot_to_render_prompt_title}}', Utils.getMessage('forgot_to_render_prompt_title')) .replace('{{forgot_to_render_prompt_info}}', Utils.getMessage('forgot_to_render_prompt_info')) .replace('{{forgot_to_render_prompt_question}}', Utils.getMessage('forgot_to_render_prompt_question')) .replace('{{forgot_to_render_prompt_close_hover}}', Utils.getMessage('forgot_to_render_prompt_close_hover')) .replace('{{forgot_to_render_back_button}}', Utils.getMessage('forgot_to_render_back_button')) .replace('{{forgot_to_render_send_button}}', Utils.getMessage('forgot_to_render_send_button')); // Get the logo image data Utils.getLocalFile( Utils.getLocalURL('/common/images/icon48.png'), 'base64', function(logoBase64) { // Do some rough template replacement html = html.replace('{{logoBase64}}', logoBase64); debugLog('getForgotToRenderPromptContent', 'got'); return responseCallback(html); }); }); } // // Begin content script code // /* Regarding Firefox and the spacebar. In Chrome, canceling the spacebar `keydown` event seems to successfully prevent the resulting `click` event on a button. This is what we'd like to have happen. In Firefox, canceling the spacebar `keydown` does *not* prevent the `click` event. This has two annoying effects for us: 1. If the user hits `space` on the Gmail Send button and they don't release right away, our message box's focused button might get immediately `click`ed. 2. If the user hits `space` to dismiss our message box, any button underneath (such as on Gmail's "Please specify at least one recipient" box) might get clicked. */ // TODO: Can we use VK_* instead? var ENTER_KEYCODE = 13; var SPACE_KEYCODE = 32; var TAB_KEYCODE = 9; var ESCAPE_KEYCODE = 27; var WATCHED_PROPERTY = 'markdownHereForgotToRenderWatched'; // Returns the correct selector to use when looking for the Send button. // Returns null if forgot-to-render should not be used here. function getForgotToRenderButtonSelector(elem) { if (elem.ownerDocument.location.host.indexOf('mail.google.') >= 0) { return '[role="button"][tabindex="1"][aria-label][data-tooltip]'; } else if (elem.ownerDocument.location.host.indexOf('fastmail.') >= 0) { return '[class~="s-send"]'; } return null; } // This function encapsulates the logic required to prevent accidental sending // of email that the user wrote in Markdown but forgot to render. function forgotToRenderIntervalCheck(focusedElem, MarkdownHere, MdhHtmlToText, marked, prefs) { if (!prefs['forgot-to-render-check-enabled-2']) { debugLog('forgotToRenderIntervalCheck', 'pref disabled'); return; } /* There are four(?) ways to send a Gmail email: 1. Click the Send button. (TODO: Is a touchscreen touch different?) 2. Put focus on the Send button (with Tab) and hit the Space key. 3. Put focus on the Send button (with Tab) and hit the Enter key. 4. With focus in the compose area or subject field, press the Ctrl+Enter (Windows, Linux) or ⌘+Enter (OSX) hotkey. * For now we're going to ignore the "or subject field" part. */ var forgotToRenderButtonSelector = getForgotToRenderButtonSelector(focusedElem); if (!forgotToRenderButtonSelector) { debugLog('forgotToRenderIntervalCheck', 'not supported'); return; } // If focus isn't in the compose body, there's nothing to do if (!MarkdownHere.elementCanBeRendered(focusedElem)) { debugLog('forgotToRenderIntervalCheck', 'cannot be rendered'); return; } // If we've already set up watchers for this compose element, skip it. if (typeof(focusedElem[WATCHED_PROPERTY]) === 'undefined') { debugLog('forgotToRenderIntervalCheck', 'setting up interceptors'); setupForgotToRenderInterceptors(focusedElem, MdhHtmlToText, marked, prefs); focusedElem[WATCHED_PROPERTY] = true; } else { debugLog('forgotToRenderIntervalCheck', 'interceptors already in place'); } } function findClosestSendButton(elem) { // This is clearly fragile and will inevitably bring us grief as Google // changes the Gmail layout, button labels, etc. But I don't know a better // way to do this. // Gmail has a very different structure in Firefox than in Chrome: it uses an // iframe with contenteditable body in the former and a simple contenteditable // div in the latter. That means that sometimes we'll be crossing iframe // boundaries and sometimes we won't. var forgotToRenderButtonSelector = getForgotToRenderButtonSelector(elem); // If we're in this function, this should be non-null, but... if (!forgotToRenderButtonSelector) { return null; } var sendButton = null; while (elem.parentNode && elem.parentNode.nodeType === elem.ELEMENT_NODE) { sendButton = elem.parentNode.querySelector(forgotToRenderButtonSelector); if (sendButton) { debugLog('findClosestSendButton', 'found'); return sendButton; } elem = elem.parentNode; } // If this appears to be in an iframe, make a recursive call. if (elem.ownerDocument.defaultView.frameElement) { return findClosestSendButton(elem.ownerDocument.defaultView.frameElement); } debugLog('findClosestSendButton', 'not found'); return null; } // Totally shuts down propagation of event, if we didn't trigger the event. function eatEvent(event) { if (event[Utils.MARKDOWN_HERE_EVENT]) { debugLog('eatEvent', 'MDH event eaten', event.type); return; } event.stopImmediatePropagation(); event.stopPropagation(); event.preventDefault(); debugLog('eatEvent', 'non-MDH event eaten', event.type); } // Sets up event listeners to capture attempts to send the email. function setupForgotToRenderInterceptors(composeElem, MdhHtmlToText, marked, prefs) { var composeSendButton = findClosestSendButton(composeElem); if (!composeSendButton) { Utils.consoleLog('Markdown Here was unable to find the Gmail "Send" button. Please let the developers know by creating an issue at: https://github.com/adam-p/markdown-here/issues'); return; } var shouldIntercept = function() { var mdMaybe = new MdhHtmlToText.MdhHtmlToText(composeElem, null, true).get(); return probablyWritingMarkdown(mdMaybe, marked, prefs); }; // Helper function to look for element within parents up to a certain point. // We use this because sometimes a click even happens on a child element of // the send button, but we still want it to count as a click on the button. var isSendButtonOrChild = function(eventTarget) { var elem = eventTarget; while (elem && elem.nodeType === elem.ELEMENT_NODE && elem !== composeSendButton.parentNode) { if (elem === composeSendButton) { return true; } elem = elem.parentNode; } return false; }; // NOTE: We are setting the event listeners on the *parent* element of the // send button and compose area. This is so that we can capture and prevent // propagation to the actual element, thereby preventing Gmail's event // listeners from firing. var composeSendButtonKeyListener = function(event) { if (isSendButtonOrChild(event.target) && (event.keyCode === ENTER_KEYCODE || event.keyCode === SPACE_KEYCODE) && shouldIntercept()) { // Gmail uses keydown to trigger its send action. Firefox fires keyup even if // keydown has been suppressed or hasn't yet been let through. // So we're going to suppress keydown and act on keyup. if (event.type === 'keydown') { eatEvent(event); } else if (event.type === 'keyup') { eatEvent(event); showForgotToRenderPromptAndRespond(composeElem, composeSendButton); } } }; var composeSendButtonClickListener = function(event) { if (isSendButtonOrChild(event.target) && !event[Utils.MARKDOWN_HERE_EVENT] && shouldIntercept()) { eatEvent(event); showForgotToRenderPromptAndRespond(composeElem, composeSendButton); } }; var sendHotkeyKeydownListener = function(event) { // Windows and Linux use Ctrl+Enter and OSX uses ⌘+Enter, so we're going // to check for either. // There is a bug in Firefox (that has bitten us before) that causes tabbing // into a `contenteditable` element to give focus to the parent `HTMLHtmlElement` // rather than the edit element. If we don't work around this, then our hotkey // interceptor won't work if the user tabs from the subject into the body // (which lots of users do). // https://bugzilla.mozilla.org/show_bug.cgi?id=740813 var ourTarget = (event.target === composeElem) || (event.target instanceof composeElem.ownerDocument.defaultView.HTMLHtmlElement && event.target === composeElem.parentNode); if (ourTarget && (event.metaKey || event.ctrlKey) && event.keyCode === ENTER_KEYCODE && shouldIntercept()) { eatEvent(event); debugLog('setupForgotToRenderInterceptors', 'sendHotkeyKeydownListener', 'capture desired event'); showForgotToRenderPromptAndRespond(composeElem, composeSendButton); } debugLog('setupForgotToRenderInterceptors', 'sendHotkeyKeydownListener', 'skipping undesired event', event.target); }; composeSendButton.parentNode.addEventListener('keydown', composeSendButtonKeyListener, true); composeSendButton.parentNode.addEventListener('keyup', composeSendButtonKeyListener, true); composeSendButton.parentNode.addEventListener('click', composeSendButtonClickListener, true); composeElem.parentNode.addEventListener('keydown', sendHotkeyKeydownListener, true); } // Returns true if `text` looks like raw Markdown, false otherwise. function probablyWritingMarkdown(mdMaybe, marked, prefs) { /* This is going to be tricksy and fraught with danger. Challenges: * If it's not sensitive enough, it's useless. * If it's too sensitive, users will be super annoyed. * Different people write different kinds of Markdown: coders use backticks, mathies use dollar signs, normal people don't use either. * Being slow would be bad. Ways I considered doing this, but discarded: * Use Highlight.js's relevance score. * Use the size of the array returned by Marked.js's lexer/parser. * Render the contents, replace `<p>` tags with newlines, do string distance. But I think there are some simple heuristics that will probably be more accurate and/or faster. */ // Ensure that we're not checking on enormous amounts of text. if (mdMaybe.length > 10000) { mdMaybe = mdMaybe.slice(0, 10000); } // TODO: Export regexes from Marked.js instead of copying them. Except... // Marked's rules use /^.../, which breaks our matching. // NOTE: It's going to be tempting to use a ton of fancy regexes, but remember // that this check is getting run every few seconds, and we don't want to // slow down the user's browser. // To that end, we're going to stop checking when we find a match. function logMatch(type, match) { var log = 'Markdown Here detected unrendered ' + type + (typeof(match.index) !== 'undefined' ? (': "' + mdMaybe.slice(match.index, match.index+10) + '"') : ''); if (log !== probablyWritingMarkdown.lastLog) { Utils.consoleLog(log); probablyWritingMarkdown.lastLog = log; } } // At least two bullet points var bulletList = mdMaybe.match(/^[*+-] /mg); if (bulletList && bulletList.length > 1) { logMatch('bullet list', bulletList); return true; } // Backticks == code. Does anyone use backticks for anything else? var backticks = mdMaybe.match(/`/); if (backticks) { logMatch('code', backticks); return true; } // Math var math = mdMaybe.match(/\$([^ \t\n\$]([^\$]*[^ \t\n\$])?)\$/); if (math) { logMatch('math', math); return true; } // We're going to look for strong emphasis (e.g., double asterisk), but not // light emphasis (e.g., single asterisk). Rationale: people use surrounding // single asterisks pretty often in ordinary, non-MD text, and we don't want // to be annoying. // TODO: If we ever get really fancy with MD detection, the presence of light // emphasis should still contribute towards the determination. var emphasis = mdMaybe.match(/__([\s\S]+?)__(?!_)|\*\*([\s\S]+?)\*\*(?!\*)/); if (emphasis) { logMatch('emphasis', emphasis); return true; } // Headers. (But not hash-mark-H1, since that seems more likely to false-positive, and // less likely to be used. And underlines of at least length 5.) var header = mdMaybe.match(/(^\s{0,3}#{2,6}[^#])|(^\s*[-=]{5,}\s*$)/m); if (header) { logMatch('header', header); return true; } // Links // I'm worried about incorrectly catching square brackets in rendered code // blocks, so we're only going to look for '](' and '][' (which still aren't // immune to the problem, but a little better). This means we won't match // reference links (where the text in the square brackes is used elsewhere for // for the link). var link = mdMaybe.match(/\]\(|\]\[/); if (link) { logMatch('link', link); return true; } return false; } function showForgotToRenderPromptAndRespond(composeElem, composeSendButton) { var sendOrGoBackToCompose = function(send) { if (send) { Utils.fireMouseClick(composeSendButton); } else { Utils.setFocus(composeElem); } }; Utils.makeRequestToPrivilegedScript( composeElem.ownerDocument, { action: 'get-forgot-to-render-prompt'}, function(response) { showHTMLForgotToRenderPrompt( response.html, composeElem, composeSendButton, sendOrGoBackToCompose); }); } // Shows prompt and then calls `callback` passing true if the email sending // should be halted. function showHTMLForgotToRenderPrompt(html, composeElem, composeSendButton, callback) { var elem, keyboardCapture, dismissPrompt, closeLink, backButton, sendButton, okayToKeyupTimeout, okayToKeyup; elem = composeSendButton.ownerDocument.createElement('div'); composeSendButton.ownerDocument.body.appendChild(elem); Utils.saferSetOuterHTML(elem, html, true); // allow style tags // Note that `elem` is no longer valid after we call Utils.saferSetOuterHTML on it. // Set focus to our first button. Utils.setFocus(composeSendButton.ownerDocument.querySelector('#markdown-here-forgot-to-render-buttons button')); // We're going to prevent `keyup` firing for a short amount of time to help // deal with late `keyup` events resulting from initial Gmail Send activation. okayToKeyup = false; okayToKeyupTimeout = function() { okayToKeyup = true; }; composeSendButton.ownerDocument.defaultView.setTimeout(okayToKeyupTimeout, 300); // Also add an Escape key handler and other keyboard shortcut disabler. // Without this, Gmail shortcuts will fire if our buttons don't have focus. // NOTE: If we don't properly remove this in every case that the prompt is // dismissed, then we'll break the user's ability to type anything. keyboardCapture = (function() { var keyboardCaptureHandler = function(event) { eatEvent(event); if (event.keyCode === ESCAPE_KEYCODE) { // We don't check okayToKeyup here, since Escape couldn't have been been // the key that launched the prompt. dismissPrompt(event.target.ownerDocument, false); } else if (event.keyCode === TAB_KEYCODE) { if (!okayToKeyup) { return; } if (event.target.ownerDocument.activeElement === backButton) { sendButton.focus(); } else { backButton.focus(); } } else if (event.keyCode === ENTER_KEYCODE || event.keyCode === SPACE_KEYCODE) { if (!okayToKeyup) { return; } if (event.ctrlKey || event.metaKey) { // This is probably a late keyup resulting from the Gmail send hotkey // (Ctrl+Enter/Cmd+Enter), so ignore it. return; } if (event.target.ownerDocument.activeElement === backButton || event.target.ownerDocument.activeElement === sendButton) { Utils.fireMouseClick(event.target.ownerDocument.activeElement); } } }; return { add: function() { // We need to respond to the `keyup` event so that it doesn't fire after // we dismiss our prompt (affecting some control in Gmail). // We need to swallow `keydown` events so that they don't trigger // keyboard shortcuts in Gmail. composeSendButton.ownerDocument.body.addEventListener('keydown', eatEvent, true); composeSendButton.ownerDocument.body.addEventListener('keyup', keyboardCaptureHandler, true); }, remove: function() { composeSendButton.ownerDocument.body.removeEventListener('keydown', eatEvent, true); composeSendButton.ownerDocument.body.removeEventListener('keyup', keyboardCaptureHandler, true); } }; })(); dismissPrompt = function(doc, send) { keyboardCapture.remove(); var forgotToRenderContent = doc.querySelector('#markdown-here-forgot-to-render'); if (forgotToRenderContent) { doc.body.removeChild(forgotToRenderContent); } callback(send); }; keyboardCapture.add(); closeLink = composeSendButton.ownerDocument.querySelector('#markdown-here-forgot-to-render-close'); closeLink.addEventListener('click', function(event) { eatEvent(event); dismissPrompt(event.target.ownerDocument, false); }); backButton = composeSendButton.ownerDocument.querySelector('#markdown-here-forgot-to-render-button-back'); backButton.addEventListener('click', function(event) { eatEvent(event); dismissPrompt(event.target.ownerDocument, false); }); sendButton = composeSendButton.ownerDocument.querySelector('#markdown-here-forgot-to-render-button-send'); sendButton.addEventListener('click', function(event) { eatEvent(event); dismissPrompt(event.target.ownerDocument, true); }); } /* End forgot-to-render ****************************************************************************** */ // Expose these functions var CommonLogic = {}; CommonLogic.getForgotToRenderPromptContent = getForgotToRenderPromptContent; CommonLogic.forgotToRenderIntervalCheck = forgotToRenderIntervalCheck; CommonLogic.probablyWritingMarkdown = probablyWritingMarkdown; var EXPORTED_SYMBOLS = ['CommonLogic']; if (typeof module !== 'undefined') { module.exports = CommonLogic; } else { this.CommonLogic = CommonLogic; this.EXPORTED_SYMBOLS = EXPORTED_SYMBOLS; } }).call(function() { return this || (typeof window !== 'undefined' ? window : global); }());
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
false
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/common/options-iframe.js
src/common/options-iframe.js
/* * Copyright Adam Pritchard 2015 * MIT License : https://adampritchard.mit-license.org/ */ function onLoad() { // The body of the iframe needs to have a (collapsed) selection range for // Markdown Here to work (simulating focus/cursor). const range = document.createRange(); range.setStart(document.body, 0); const sel = document.getSelection(); sel.removeAllRanges(); sel.addRange(range); const demoMarkdown = Utils.getMessage('options_page__preview_markdown'); Utils.saferSetInnerHTML(document.body, demoMarkdown); } document.addEventListener('DOMContentLoaded', onLoad, false);
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
false
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/common/jsHtmlToText.js
src/common/jsHtmlToText.js
/* Copyright (C) 2006 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. HTML decoding functionality provided by: https://code.google.com/archive/p/google-trekker/ */ /* adam-p: modified to be a module */ ;(function() { function htmlToText(html, extensions) { var text = html, i; if (extensions && extensions['preprocessing']) text = extensions['preprocessing'](text); text = text // Remove line breaks .replace(/(?:\n|\r\n|\r)/ig, " ") // Remove content in script tags. .replace(/<\s*script[^>]*>[\s\S]*?<\/script>/mig, "") // Remove content in style tags. .replace(/<\s*style[^>]*>[\s\S]*?<\/style>/mig, "") // Remove content in comments. .replace(/<!--.*?-->/mig, "") // Remove !DOCTYPE .replace(/<!DOCTYPE.*?>/ig, ""); /* I scanned https://en.wikipedia.org/wiki/HTML_element for all html tags. I put those tags that should affect plain text formatting in two categories: those that should be replaced with two newlines and those that should be replaced with one newline. */ if (extensions && extensions['tagreplacement']) text = extensions['tagreplacement'](text); var doubleNewlineTags = ['p', 'h[1-6]', 'dl', 'dt', 'dd', 'ol', 'ul', 'dir', 'address', 'blockquote', 'center', 'div', 'hr', 'pre', 'form', 'textarea', 'table']; var singleNewlineTags = ['li', 'del', 'ins', 'fieldset', 'legend', 'tr', 'th', 'caption', 'thead', 'tbody', 'tfoot']; for (i = 0; i < doubleNewlineTags.length; i++) { var r = RegExp('</?\\s*' + doubleNewlineTags[i] + '[^>]*>', 'ig'); text = text.replace(r, '\n\n'); } for (i = 0; i < singleNewlineTags.length; i++) { var r = RegExp('<\\s*' + singleNewlineTags[i] + '[^>]*>', 'ig'); text = text.replace(r, '\n'); } // Replace <br> and <br/> with a single newline text = text.replace(/<\s*br[^>]*\/?\s*>/ig, '\n'); text = text // Remove all remaining tags. .replace(/(<([^>]+)>)/ig,"") // Make sure there are never more than two // consecutive linebreaks. .replace(/\n{2,}/g,"\n\n") // Remove newlines at the beginning of the text. .replace(/^\n+/,"") // Remove newlines at the end of the text. .replace(/\n+$/,"") // Decode HTML entities. .replace(/&([^;]+);/g, decodeHtmlEntity); /* adam-p: make trailing whitespace stripping optional */ if (!extensions || !extensions['allowTrailingWhitespace']) { text = text // Trim rightmost whitespaces for all lines .replace(/([^\n\S]+)\n/g,"\n") .replace(/([^\n\S]+)$/,""); } if (extensions && extensions['postprocessing']) text = extensions['postprocessing'](text); return text; } function decodeHtmlEntity(m, n) { // Determine the character code of the entity. Range is 0 to 65535 // (characters in JavaScript are Unicode, and entities can represent // Unicode characters). var code; // Try to parse as numeric entity. This is done before named entities for // speed because associative array lookup in many JavaScript implementations // is a linear search. if (n.substr(0, 1) == '#') { // Try to parse as numeric entity if (n.substr(1, 1) == 'x') { // Try to parse as hexadecimal code = parseInt(n.substr(2), 16); } else { // Try to parse as decimal code = parseInt(n.substr(1), 10); } } else { // Try to parse as named entity code = ENTITIES_MAP[n]; } // If still nothing, pass entity through return (code === undefined || code === NaN) ? '&' + n + ';' : String.fromCharCode(code); } var ENTITIES_MAP = { 'nbsp' : 160, 'iexcl' : 161, 'cent' : 162, 'pound' : 163, 'curren' : 164, 'yen' : 165, 'brvbar' : 166, 'sect' : 167, 'uml' : 168, 'copy' : 169, 'ordf' : 170, 'laquo' : 171, 'not' : 172, 'shy' : 173, 'reg' : 174, 'macr' : 175, 'deg' : 176, 'plusmn' : 177, 'sup2' : 178, 'sup3' : 179, 'acute' : 180, 'micro' : 181, 'para' : 182, 'middot' : 183, 'cedil' : 184, 'sup1' : 185, 'ordm' : 186, 'raquo' : 187, 'frac14' : 188, 'frac12' : 189, 'frac34' : 190, 'iquest' : 191, 'Agrave' : 192, 'Aacute' : 193, 'Acirc' : 194, 'Atilde' : 195, 'Auml' : 196, 'Aring' : 197, 'AElig' : 198, 'Ccedil' : 199, 'Egrave' : 200, 'Eacute' : 201, 'Ecirc' : 202, 'Euml' : 203, 'Igrave' : 204, 'Iacute' : 205, 'Icirc' : 206, 'Iuml' : 207, 'ETH' : 208, 'Ntilde' : 209, 'Ograve' : 210, 'Oacute' : 211, 'Ocirc' : 212, 'Otilde' : 213, 'Ouml' : 214, 'times' : 215, 'Oslash' : 216, 'Ugrave' : 217, 'Uacute' : 218, 'Ucirc' : 219, 'Uuml' : 220, 'Yacute' : 221, 'THORN' : 222, 'szlig' : 223, 'agrave' : 224, 'aacute' : 225, 'acirc' : 226, 'atilde' : 227, 'auml' : 228, 'aring' : 229, 'aelig' : 230, 'ccedil' : 231, 'egrave' : 232, 'eacute' : 233, 'ecirc' : 234, 'euml' : 235, 'igrave' : 236, 'iacute' : 237, 'icirc' : 238, 'iuml' : 239, 'eth' : 240, 'ntilde' : 241, 'ograve' : 242, 'oacute' : 243, 'ocirc' : 244, 'otilde' : 245, 'ouml' : 246, 'divide' : 247, 'oslash' : 248, 'ugrave' : 249, 'uacute' : 250, 'ucirc' : 251, 'uuml' : 252, 'yacute' : 253, 'thorn' : 254, 'yuml' : 255, 'quot' : 34, 'amp' : 38, 'lt' : 60, 'gt' : 62, 'OElig' : 338, 'oelig' : 339, 'Scaron' : 352, 'scaron' : 353, 'Yuml' : 376, 'circ' : 710, 'tilde' : 732, 'ensp' : 8194, 'emsp' : 8195, 'thinsp' : 8201, 'zwnj' : 8204, 'zwj' : 8205, 'lrm' : 8206, 'rlm' : 8207, 'ndash' : 8211, 'mdash' : 8212, 'lsquo' : 8216, 'rsquo' : 8217, 'sbquo' : 8218, 'ldquo' : 8220, 'rdquo' : 8221, 'bdquo' : 8222, 'dagger' : 8224, 'Dagger' : 8225, 'permil' : 8240, 'lsaquo' : 8249, 'rsaquo' : 8250, 'euro' : 8364 }; var EXPORTED_SYMBOLS = ['htmlToText']; if (typeof module !== 'undefined') { module.exports = htmlToText; } else { this.htmlToText = htmlToText; this.EXPORTED_SYMBOLS = EXPORTED_SYMBOLS; } }).call(function() { return this || (typeof window !== 'undefined' ? window : global); }());
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
false
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/common/markdown-here.js
src/common/markdown-here.js
/* * Copyright Adam Pritchard 2015 * MIT License : https://adampritchard.mit-license.org/ */ /* * This file is the heart of Markdown Here. It decides whether we're rendering * or reverting; whether we're doing a selection or the whole thing; and * actually does it (calling out for the final render). */ /* Regarding our rendered Markdown "wrappers": When we render a some Markdown -- whether it's the entire content or sub-selection -- we need to save the original Markdown (actually, Markdown-in-HTML) somewhere so that we can later unrender if the user requests it. Where to save the original markdown is a difficult decision, since many web interface will disallow or strip certain attributes or attribute values (etc.). We have found that the `title` attribute of a `<div>` element is preserved. (In the sites tested at the time of writing.) So we're create an empty `<div>`, and store the original MD in the `title` attribute, prefixed with a marker (`MDH:`) to help prevent false positives when looking for wrappers. Then, looking for "wrappers" will involve looking for the "div with original MD in title" and then getting its parent. (The reason that we're not storing the MD in the title of the wrapper itself is that that will result in the raw MD being shown as a tooltip when the user hovers over the wrapper. The extra empty div won't have any size, so there won't be a hover problem.) For info about the ideas we had and experiments we ran, see: https://github.com/adam-p/markdown-here/issues/85 */ ;(function() { "use strict"; /* global module:false Utils */ var WRAPPER_TITLE_PREFIX = 'MDH:'; // For debugging purposes. An external service is required to log with Firefox. var mylog = function() {}; // Finds and returns the page element that currently has focus. Drills down into // iframes if necessary. function findFocusedElem(document) { var focusedElem = document.activeElement; // Tests if it's possible to access the iframe contentDocument without throwing // an exception. function iframeAccessOkay(focusedElem) { // Fix #173: https://github.com/adam-p/markdown-here/issues/173 // Fix #435: https://github.com/adam-p/markdown-here/issues/435 // If the focus is in an iframe with a different origin, then attempting to // access focusedElem.contentDocument will fail with a `SecurityError`: // "Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "http://jsbin.io" from accessing a cross-origin frame." // Rather than spam the console with exceptions, we'll treat this as an // unrenderable situation (which it is). try { var _ = focusedElem.contentDocument; } catch (e) { // TODO: Check that this is actually a SecurityError and re-throw if it's not? return false; } return true; } if (!iframeAccessOkay(focusedElem)) { return null; } // If the focus is within an iframe, we'll have to drill down to get to the // actual element. while (focusedElem && focusedElem.contentDocument) { focusedElem = focusedElem.contentDocument.activeElement; if (!iframeAccessOkay(focusedElem)) { return null; } } // There's a bug in Firefox/Thunderbird that we need to work around. For // details see https://github.com/adam-p/markdown-here/issues/31 // The short version: Sometimes we'll get the <html> element instead of <body>. if (focusedElem instanceof document.defaultView.HTMLHtmlElement) { focusedElem = focusedElem.ownerDocument.body; } return focusedElem; } // Returns true if the given element can be properly rendered (i.e., if it's // a rich-edit compose element). function elementCanBeRendered(elem) { // See here for more info about what we're checking: // https://stackoverflow.com/a/3333679/729729 return (elem.contentEditable === true || elem.contentEditable === 'true' || elem.contenteditable === true || elem.contenteditable === 'true' || (elem.ownerDocument && elem.ownerDocument.designMode === 'on')); } // Get the currectly selected range. If there is no selected range (i.e., it is // collapsed), then contents of the currently focused element will be selected. // Returns null if no range is selected nor can be selected. function getOperationalRange(focusedElem) { var selection, range, sig; selection = focusedElem.ownerDocument.defaultView.getSelection(); if (selection.rangeCount < 1) { return null; } range = selection.getRangeAt(0); // We're going to work around some weird OSX+Chrome behaviour where if you // right-click on a word it gets selected, which then causes us to render just // that one word and look dumb and be wrong. if ((range.toString().length === 0) || (typeof(navigator) !== 'undefined' && navigator.userAgent.indexOf('OS X') >= 0 && range.toString().match(/^\b\w+\b$/))) { range.collapse(true); } if (range.collapsed) { // If there's no actual selection, select the contents of the focused element. range.selectNodeContents(focusedElem); } // Does our range include a signature? If so, remove it. sig = findSignatureStart(focusedElem); if (sig) { // If the sig is an element node, set a class indicating that it's a sig. // This gives us (or the user) the option of styling differently. if (sig.nodeType === sig.ELEMENT_NODE) { sig.classList.add('markdown-here-signature'); } if (range.isPointInRange(sig, 0)) { range.setEndBefore(sig); } } return range; } // A signature is indicated by the last `'-- '` text node (or something like it). // Returns the sig start element, or null if one is not found. // NOTE: I would really prefer that this be in markdown-render.js with the other // exclusion code. But I'm not sure how to find the sig as well without being // able to traverse the DOM. (Surely with regexes and parsing... someday.) function findSignatureStart(startElem) { var i, child, recurseReturn, sig; sig = null; for (i = 0; i < startElem.childNodes.length; i++) { child = startElem.childNodes[i]; if (child.nodeType === child.TEXT_NODE) { // Thunderbird wraps the sig in a `<pre>`, so there's a newline. // Hand-written sigs (including Hotmail and Yahoo) are `'--&nbsp;'` (aka \u00a0). // Gmail auto-inserted sigs are `'-- '` (plain space). if (child.nodeValue.search(/^--[\s\u00a0]+(\n|$)/) === 0) { // Assume that the entire parent element belongs to the sig only if the // `'--'` bit is the at the very start of the parent. if (startElem.firstChild === child) { sig = startElem; } else { sig = child; } } } else if (['BLOCKQUOTE'].indexOf(child.nodeName) < 0) { recurseReturn = findSignatureStart(child, true); // Did the recursive call find it? if (recurseReturn) { sig = recurseReturn; } } } return sig; } /** * Replaces the contents of `range` with the HTML string in `html`. * Returns the element that is created from `html`. * @param {Range} range * @param {string} html * @returns {Element} */ function replaceRange(range, html) { range.deleteContents(); // Create a DocumentFragment to insert and populate it with HTML const documentFragment = Utils.safelyParseHTML(html, range.startContainer.ownerDocument); // After inserting the node contents, the node is empty. So we need to save a // reference to the element that we need to return. const newElement = documentFragment.firstChild; range.insertNode(documentFragment); // In some clients (and maybe some versions of those clients), on some pages, // the newly inserted rendered Markdown will be selected. It looks better and // is slightly less annoying if the text is not selected, and consistency // across platforms is good. So we're going to collapse the selection. // Note that specifying the `toStart` argument to `true` seems to be necessary // in order to actually get a cursor in the editor. // Fixes #427: https://github.com/adam-p/markdown-here/issues/427 range.collapse(true); return newElement; } // Returns the stylesheet for our styles. function getMarkdownStylesheet(elem, css) { var styleElem, stylesheet, i; // We have to actually create a style element in the document, then pull the // stylesheet out of it (and remove the element). // Create a style element styleElem = elem.ownerDocument.createElement('style'); styleElem.setAttribute('title', 'markdown-here-styles'); // Set the CSS in the style element styleElem.appendChild(elem.ownerDocument.createTextNode(css)); // Put the style element in the DOM under `elem` elem.appendChild(styleElem); // Find the stylesheet that we just created for (i = 0; i < elem.ownerDocument.styleSheets.length; i++) { if (elem.ownerDocument.styleSheets[i].title === 'markdown-here-styles') { stylesheet = elem.ownerDocument.styleSheets[i]; break; } } if (!stylesheet) { throw 'Markdown Here stylesheet not found!'; } // Take the stylesheet element out of the DOM elem.removeChild(styleElem); return stylesheet; } // Applies our styling explicitly to the elements under `wrapperElem`. function makeStylesExplicit(wrapperElem, css) { var stylesheet, rule, selectorMatches, i, j, styleAttr, elem; stylesheet = getMarkdownStylesheet(wrapperElem, css); for (i = 0; i < stylesheet.cssRules.length; i++) { rule = stylesheet.cssRules[i]; // Note that the CSS should not have any rules that use "body" or "html". // We're starting our search one level above the wrapper, which means we // might match stuff outside of our wrapper. We'll have to double-check below. selectorMatches = wrapperElem.parentNode.querySelectorAll(rule.selectorText); for (j = 0; j < selectorMatches.length; j++) { elem = selectorMatches[j]; // Make sure the element is inside our wrapper (or is our wrapper). if (elem !== wrapperElem && !Utils.isElementDescendant(wrapperElem, elem)) { continue; } // Make sure the selector match isn't inside an exclusion block. // The check for `elem.classList` stop us if we hit a non-element node // while going up through the parents. while (elem && (typeof(elem.classList) !== 'undefined')) { if (elem.classList.contains('markdown-here-exclude')) { elem = 'excluded'; break; } elem = elem.parentNode; } if (elem === 'excluded') { // Don't style this element. continue; } // Get the existing styles for the element. styleAttr = selectorMatches[j].getAttribute('style') || ''; // Append the new styles to the end of the existing styles. This will // give the new ones precedence if any are the same as existing ones. // Make sure existing styles end with a semicolon. if (styleAttr && styleAttr.search(/;[\s]*$/) < 0) { styleAttr += '; '; } styleAttr += rule.style.cssText; // Set the styles back. selectorMatches[j].setAttribute('style', styleAttr); } } } function hasParentElementOfTagName(element, tagName) { var parent; tagName = tagName.toUpperCase(); parent = element.parentNode; while (parent) { if (parent.nodeName === tagName) { return true; } parent = parent.parentNode; } return false; } // Looks for valid raw-MD-holder element under `elem`. Only MDH wrappers will // have such an element. // Returns null if no raw-MD-holder element is found; otherwise returns that element. function findElemRawHolder(elem) { // A raw-MD-holder element has a specially prefixed title and must be an // immediate child of `elem`. // // To restrict our selector to only immediate children of elem, we would // use `:scope > whatever`, but scope is not supported widely enough yet. // See: https://developer.mozilla.org/en-US/docs/Web/CSS/:scope#Browser_compatibility // // If we just take the first `querySelector` result, we may get the wrong // raw-MD-holder element -- a grandchild -- and incorrectly assume that // `elem` is not a wrapper element. So we'll check all query results and // only return false if none of them are immediate children. // Here's an example of a failure case email if we didn't do that: // New rendered MD in a reply here. // On Thu, Aug 13, 2015 at 9:08 PM, Billy Bob wrote: // | Rendered MD in original email here. // | [invisible raw MD holder elem for original email] // [invisible raw MD holder elem for reply] // `querySelector` would return the holder inside the original email. // This scenario is issue #297 https://github.com/adam-p/markdown-here/issues/297 var rawHolders = elem.querySelectorAll('[title^="' + WRAPPER_TITLE_PREFIX + '"]'); for (var i = 0; i < rawHolders.length; i++) { if (// The above `querySelector` will also look at grandchildren of // `elem`, which we don't want. rawHolders[i].parentNode === elem && // Skip all wrappers that are in a `blockquote`. We don't want to revert // Markdown that was sent to us. !hasParentElementOfTagName(elem, 'BLOCKQUOTE')) { return rawHolders[i]; } } return null; } // Determine if the given element is a MDH wrapper element. function isWrapperElem(elem) { return true && // Make sure the candidate is an element node elem.nodeType === elem.ELEMENT_NODE && // And is not a blockquote, so we ignore replies elem.tagName.toUpperCase() !== 'BLOCKQUOTE' && // And has a raw-MD-holder element findElemRawHolder(elem) !== null; } // Finds the wrapper element that's above the current cursor position and // returns it. Returns falsy if there is no wrapper. function findMarkdownHereWrapper(focusedElem) { var selection, range, wrapper = null; selection = focusedElem.ownerDocument.defaultView.getSelection(); if (selection.rangeCount < 1) { return null; } range = selection.getRangeAt(0); wrapper = range.commonAncestorContainer; while (wrapper && !isWrapperElem(wrapper)) { wrapper = wrapper.parentNode; } return wrapper; } // Finds all Markdown Here wrappers in the given range. Returns an array of the // wrapper elements, or null if no wrappers found. function findMarkdownHereWrappersInRange(range) { // Adapted from: https://stackoverflow.com/a/1483487/729729 var containerElement = range.commonAncestorContainer; if (containerElement.nodeType != containerElement.ELEMENT_NODE) { containerElement = containerElement.parentNode; } var elems = []; var nodeTester = function(elem) { if (elem.nodeType === elem.ELEMENT_NODE && Utils.rangeIntersectsNode(range, elem) && isWrapperElem(elem)) { elems.push(elem); } }; Utils.walkDOM(containerElement, nodeTester); /* // This code is probably superior, but TreeWalker is not supported by Postbox. // If this ends up getting used, it should probably be moved into walkDOM // (or walkDOM should be removed). var nodeTester = function(node) { if (node.nodeType !== node.ELEMENT_NODE || !Utils.rangeIntersectsNode(range, node) || !isWrapperElem(node)) { return node.ownerDocument.defaultView.NodeFilter.FILTER_SKIP; } return node.ownerDocument.defaultView.NodeFilter.FILTER_ACCEPT; }; var treeWalker = containerElement.ownerDocument.createTreeWalker( containerElement, containerElement.ownerDocument.defaultView.NodeFilter.SHOW_ELEMENT, nodeTester, false); var elems = []; while (treeWalker.nextNode()) { elems.push(treeWalker.currentNode); } */ return elems.length ? elems : null; } // Converts the Markdown in the user's compose element to HTML and replaces it. // If `selectedRange` is null, then the entire email is being rendered. function renderMarkdown(focusedElem, selectedRange, markdownRenderer, renderComplete) { var originalHtml = Utils.getDocumentFragmentHTML(selectedRange.cloneContents()); // Call to the extension main code to actually do the md->html conversion. markdownRenderer(focusedElem, selectedRange, function(mdHtml, mdCss) { var wrapper, rawHolder; // Store the original Markdown-in-HTML to the `title` attribute of a separate, // invisible-ish `div`. We have found that Gmail, Evernote, etc. leave the // title intact when saving. // `&#8203;` is a zero-width space: https://en.wikipedia.org/wiki/Zero-width_space // Thunderbird will discard the `div` if there's no content. rawHolder = '<div ' + 'title="' + WRAPPER_TITLE_PREFIX + Utils.utf8StringToBase64(originalHtml) + '" ' + 'style="height:0;width:0;max-height:0;max-width:0;overflow:hidden;font-size:0em;padding:0;margin:0;" ' + '>&#8203;</div>'; // Wrap our pretty HTML in a <div> wrapper. // We'll use the wrapper as a marker to indicate that we're in a rendered state. mdHtml = '<div class="markdown-here-wrapper" ' + 'data-md-url="' + Utils.getTopURL(focusedElem.ownerDocument.defaultView, true) + '">' + mdHtml + rawHolder + '</div>'; wrapper = replaceRange(selectedRange, mdHtml); // Some webmail (Gmail) strips off any external style block. So we need to go // through our styles, explicitly applying them to matching elements. makeStylesExplicit(wrapper, mdCss); // Monitor for changes to the content of the rendered MD. This will help us // prevent the user from silently losing changes later. // We're going to set this up after a short timeout, to help prevent false // detections based on automatic changes by the host site. wrapper.ownerDocument.defaultView.setTimeout(function addMutationObserver() { var SupportedMutationObserver = wrapper.ownerDocument.defaultView.MutationObserver || wrapper.ownerDocument.defaultView.WebKitMutationObserver; if (typeof(SupportedMutationObserver) !== 'undefined') { var observer = new SupportedMutationObserver(function(mutations) { wrapper.setAttribute('markdown-here-wrapper-content-modified', true); observer.disconnect(); }); observer.observe(wrapper, { childList: true, characterData: true, subtree: true }); } }, 100); renderComplete(); }); } // Revert the rendered Markdown wrapperElem back to its original form. function unrenderMarkdown(wrapperElem) { var rawHolder = findElemRawHolder(wrapperElem); // Not checking for success of that call, since we shouldn't be here if there // isn't a wrapper. var originalMdHtml = rawHolder.getAttribute('title'); originalMdHtml = originalMdHtml.slice(WRAPPER_TITLE_PREFIX.length).replace(/\n/g, ''); // Thunderbird breaks the long title up into multiple lines, which // wrecks our ability to un-base64 it. So strip whitespace. originalMdHtml = originalMdHtml.replace(/\s/g, ''); originalMdHtml = Utils.base64ToUTF8String(originalMdHtml); Utils.saferSetOuterHTML(wrapperElem, originalMdHtml); } // Exported function. // The context menu handler. Does the rendering or unrendering, depending on the // state of the email compose element and the current selection. // @param `document` The document object containing the email compose element. // (Actually, it can be any document above the compose element. We'll // drill down to find the correct element and document.) // @param `markdownRenderer` The function that provides raw-Markdown-in-HTML // to pretty-Markdown-in-HTML rendering service. // @param `logger` A function that can be used for logging debug messages. May // be null. // @param `renderComplete` Callback that will be called when a render or unrender // has completed. Passed two arguments: `elem` // (the element de/rendered) and `rendered` (boolean, // true if rendered, false if derendered). // @returns True if successful, otherwise an error message that should be shown // to the user. function markdownHere(document, markdownRenderer, logger, renderComplete) { if (logger) { mylog = logger; } // If the cursor (or current selection) is in a Markdown Here wrapper, then // we're reverting that wrapper back to Markdown. If there's a selection that // contains one or more wrappers, then we're reverting those wrappers back to // Markdown. // Otherwise, we're rendering. If there's a selection, then we're rendering // the selection. If not, then we're rendering the whole email. var wrappers, outerWrapper, focusedElem, range, i; focusedElem = findFocusedElem(document); if (!focusedElem || !focusedElem.ownerDocument) { return 'Could not find focused element'; } // Look for existing rendered-Markdown wrapper to revert. outerWrapper = findMarkdownHereWrapper(focusedElem); if (outerWrapper) { // There's a wrapper above us. wrappers = [outerWrapper]; } else { // Are there wrappers in our selection? range = getOperationalRange(focusedElem); if (!range) { return Utils.getMessage('nothing_to_render'); } // Look for wrappers in the range under consideration. wrappers = findMarkdownHereWrappersInRange(range); } // If we've found wrappers, then we're reverting. // Otherwise, we're rendering. if (wrappers && wrappers.length > 0) { var yesToAll = false; for (i = 0; i < wrappers.length; i++) { // Has the content been modified by the user since rendering if (wrappers[i].getAttribute('markdown-here-wrapper-content-modified') && !yesToAll) { if (wrappers[i].ownerDocument.defaultView.confirm(Utils.getMessage('unrendering_modified_markdown_warning'))) { yesToAll = true; } else { break; } } unrenderMarkdown(wrappers[i]); } if (renderComplete) { renderComplete(focusedElem, false); } } else { renderMarkdown( focusedElem, range, markdownRenderer, function() { if (renderComplete) { renderComplete(focusedElem, true); } }); } return true; } // We also export a couple of utility functions markdownHere.findFocusedElem = findFocusedElem; markdownHere.elementCanBeRendered = elementCanBeRendered; var EXPORTED_SYMBOLS = ['markdownHere']; if (typeof module !== 'undefined') { module.exports = markdownHere; } else { this.markdownHere = markdownHere; this.EXPORTED_SYMBOLS = EXPORTED_SYMBOLS; } }).call(function() { return this || (typeof window !== 'undefined' ? window : global); }());
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
false
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/common/options.js
src/common/options.js
/* * Copyright Adam Pritchard 2015 * MIT License : https://adampritchard.mit-license.org/ */ "use strict"; /* jshint browser:true, sub:true */ /* global OptionsStore:false, chrome:false, marked:false, markdownHere:false, Utils:false, MdhHtmlToText:false */ /* * Main script file for the options page. */ let cssEdit, cssSyntaxEdit, cssSyntaxSelect, rawMarkdownIframe, savedMsg, mathEnable, mathEdit, forgotToRenderCheckEnabled, headerAnchorsEnabled, gfmLineBreaksEnabled; let loaded = false; function onLoad() { localize(); // Set up our control references. cssEdit = document.getElementById('css-edit'); cssSyntaxEdit = document.getElementById('css-syntax-edit'); cssSyntaxSelect = document.getElementById('css-syntax-select'); rawMarkdownIframe = document.getElementById('rendered-markdown'); savedMsg = document.getElementById('saved-msg'); mathEnable = document.getElementById('math-enable'); mathEdit = document.getElementById('math-edit'); forgotToRenderCheckEnabled = document.getElementById('forgot-to-render-check-enabled'); headerAnchorsEnabled = document.getElementById('header-anchors-enabled'); gfmLineBreaksEnabled = document.getElementById('gfm-line-breaks-enabled'); rawMarkdownIframe.addEventListener('load', () => renderMarkdown()); rawMarkdownIframe.src = Utils.getLocalURL('/common/options-iframe.html'); forgotToRenderCheckEnabled.addEventListener('click', handleForgotToRenderChange, false); document.getElementById('extensions-shortcut-link').addEventListener('click', function(event) { event.preventDefault(); chrome.tabs.create({ url: 'chrome://extensions/shortcuts' }); }); // Update the hotkey/shortcut value chrome.commands.getAll().then(commands => { const shortcut = commands[0].shortcut; if (!shortcut) { // No shortcut set, or a conflict (that we lose) document.querySelector('.hotkey-current-error').style.display = ''; document.querySelectorAll('.hotkey-error-hide').forEach(el => el.style.display = 'none'); } else { document.querySelectorAll('.hotkey-current').forEach(el => el.textContent = shortcut); } }); // Listen for runtime messages from the background script chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { if (request.action === 'button-click') { // Handle button click from background script by toggling markdown markdownToggle(); } return false; // Synchronous response }); // // Syntax highlighting styles and selection // // Get the available highlight.js styles. Utils.getLocalFile( Utils.getLocalURL('/common/highlightjs/styles/styles.json'), 'json', function(syntaxStyles) { for (var name in syntaxStyles) { cssSyntaxSelect.options.add(new Option(name, syntaxStyles[name])); } cssSyntaxSelect.options.add(new Option(Utils.getMessage('currently_in_use'), '')); cssSyntaxSelect.selectedIndex = cssSyntaxSelect.options.length - 1; cssSyntaxSelect.addEventListener('change', cssSyntaxSelectChange); }); // // Restore previously set options (asynchronously) // var optionsGetSuccessful = false; OptionsStore.get(function(prefs) { cssEdit.value = prefs['main-css']; cssSyntaxEdit.value = prefs['syntax-css']; mathEnable.checked = prefs['math-enabled']; mathEdit.value = prefs['math-value']; forgotToRenderCheckEnabled.checked = prefs['forgot-to-render-check-enabled-2']; headerAnchorsEnabled.checked = prefs['header-anchors-enabled']; gfmLineBreaksEnabled.checked = prefs['gfm-line-breaks-enabled']; // Start watching for changes to the styles. setInterval(checkChange, 100); optionsGetSuccessful = true; }); // Load the changelist section loadChangelist(); showDonatePlea(); // Special effort is required to open the test page in these clients. if (navigator.userAgent.indexOf('Thunderbird') >= 0 || navigator.userAgent.indexOf('Zotero') >= 0) { const testsLink = document.getElementById('tests-link'); testsLink.addEventListener('click', function(event) { event.preventDefault(); const link = testsLink.querySelector('a'); Utils.makeRequestToPrivilegedScript( document, { action: 'open-tab', url: link.href }); }); } // Hide the tests link if the page isn't available. It may be stripped out // of extension packages. // Check if our test file exists. Note that we can't use Utils.getLocalFile as it throws // an asynchronous error if the file isn't found. // TODO: When Utils.getLocalFile is changed to return a promise, use it here. fetch('./test/index.html') .then(response => { if (!response.ok) { // The test files aren't present, so hide the button. document.getElementById('tests-link').style.display = 'none'; } else { // When the file is absent, Firefox still gives a 200 status, but will throw an // error when the response is read. return response.text(); } }) .catch(err => { // The test files aren't present, so hide the button. document.getElementById('tests-link').style.display = 'none'; }); // Older Thunderbird may try to open this options page in a new ChromeWindow, and it // won't work. So in that case we need to tell the user how they can actually open the // options page. This is pretty ungraceful, but few users will encounter it, and fewer as // time goes on. setTimeout(function() { if (!optionsGetSuccessful) { alert('It looks like you are running an older version of Thunderbird.\nOpen the Markdown Here Options via the message window Tools menu.'); window.close(); } }, 500); loaded = true; } document.addEventListener('DOMContentLoaded', onLoad, false); function localize() { const elements = document.querySelectorAll('[data-i18n]'); elements.forEach(function(element) { const messageID = 'options_page__' + element.dataset.i18n; if (element.tagName.toUpperCase() === 'TITLE') { element.innerText = Utils.getMessage(messageID); } else { Utils.saferSetInnerHTML(element, Utils.getMessage(messageID)); } }); // Take this opportunity to show appropriate size images for the pixel // density. This saves us from having to make the `img` tags in the // translated content more complex. // TODO: Change to media queries (and so use background-image style). if (window.devicePixelRatio === 2) { const imageMap = [ ['images/icon16.png', 'images/icon32.png'], ['images/icon16-button.png', 'images/icon32-button.png'], ['images/icon16-monochrome.png', 'images/icon32-monochrome.png'], ['images/icon16-button-monochrome.png', 'images/icon32-button-monochrome.png'], ['images/icon16-button-disabled.png', 'images/icon32-button-disabled.png'] ]; imageMap.forEach(function([oldSrc, newSrc]) { const imgs = document.querySelectorAll(`img[src="${oldSrc}"]`); imgs.forEach(function(img) { img.style.width = '16px'; img.src = newSrc; }); }); } } // If the CSS changes and the Markdown compose box is rendered, update the // rendering by toggling twice. If the compose box is not rendered, do nothing. // Groups changes together rather than on every keystroke. var lastOptions = ''; var lastChangeTime = null; var firstSave = true; function checkChange() { var newOptions = cssEdit.value + cssSyntaxEdit.value + mathEnable.checked + mathEdit.value + forgotToRenderCheckEnabled.checked + headerAnchorsEnabled.checked + gfmLineBreaksEnabled.checked; if (newOptions !== lastOptions) { // CSS has changed. lastOptions = newOptions; lastChangeTime = new Date(); } else { // No change since the last check. // There's a delicate balance to choosing this apply/save-change timeout value. // We want the user to see the effects of their change quite quickly, but // we don't want to spam our saves (because there are quota limits). But we // have to save before we can re-render (the rendering using the saved values). if (lastChangeTime && (new Date() - lastChangeTime) > 400) { // Sufficient time has passed since the last change -- time to save. lastChangeTime = null; OptionsStore.set( { 'main-css': cssEdit.value, 'syntax-css': cssSyntaxEdit.value, 'math-enabled': mathEnable.checked, 'math-value': mathEdit.value, 'forgot-to-render-check-enabled-2': forgotToRenderCheckEnabled.checked, 'header-anchors-enabled': headerAnchorsEnabled.checked, 'gfm-line-breaks-enabled': gfmLineBreaksEnabled.checked }, function() { updateMarkdownRender(); // Show the "saved changes" message, unless this is the first save // (i.e., the one when the user first opens the options window). if (!firstSave) { savedMsg.classList.add('showing'); // Hide it a bit later. // Alternatively, could use the 'transitionend' event. But this way // we control how long it shows. setTimeout(function() { savedMsg.classList.remove('showing'); }, 2000); } firstSave = false; }); } } } // This function stolen entirely from contentscript.js and ff-overlay.js function requestMarkdownConversion(elem, range, callback) { var mdhHtmlToText = new MdhHtmlToText.MdhHtmlToText(elem, range); Utils.makeRequestToPrivilegedScript( document, { action: 'render', mdText: mdhHtmlToText.get() }, function(response) { var renderedMarkdown = mdhHtmlToText.postprocess(response.html); callback(renderedMarkdown, response.css); }); } // Render the sample Markdown. function renderMarkdown(postRenderCallback) { if (rawMarkdownIframe.contentDocument.querySelector('.markdown-here-wrapper')) { // Already rendered. if (postRenderCallback) postRenderCallback(); return; } // Begin rendering. markdownHere(rawMarkdownIframe.contentDocument, requestMarkdownConversionInterceptor); // To figure out when the (asynchronous) rendering is complete -- so we // can call the `postRenderCallback` -- we'll intercept the callback used // by the rendering service. function requestMarkdownConversionInterceptor(elem, range, callback) { function callbackInterceptor() { callback.apply(null, arguments); // Rendering done. Call callback. if (postRenderCallback) postRenderCallback(); } // Call the real rendering service. requestMarkdownConversion(elem, range, callbackInterceptor); } } // Re-render already-rendered sample Markdown. function updateMarkdownRender() { if (!rawMarkdownIframe.contentDocument.querySelector('.markdown-here-wrapper')) { // Not currently rendered, so nothing to update. return; } // To mitigate flickering, hide the iframe during rendering. rawMarkdownIframe.style.visibility = 'hidden'; // Unrender markdownHere(rawMarkdownIframe.contentDocument, requestMarkdownConversion); // Re-render renderMarkdown(function() { rawMarkdownIframe.style.visibility = 'visible'; }); } // Toggle the render state of the sample Markdown. function markdownToggle() { markdownHere(rawMarkdownIframe.contentDocument, requestMarkdownConversion); } document.querySelector('#markdown-toggle-button').addEventListener('click', markdownToggle, false); // Reset the main CSS to default. function resetCssEdit() { // Get the default value. Utils.getLocalFile( OptionsStore.defaults['main-css']['__defaultFromFile__'], OptionsStore.defaults['main-css']['__dataType__'], function(defaultValue) { cssEdit.value = defaultValue; }); } document.getElementById('reset-button').addEventListener('click', resetCssEdit, false); // The syntax hightlighting CSS combo-box selection changed. function cssSyntaxSelectChange() { var selected = cssSyntaxSelect.options[cssSyntaxSelect.selectedIndex].value; if (!selected) { // This probably indicates that the user selected the "currently in use" // option, which is by definition what is in the edit box. return; } // Remove the "currently in use" option, since it doesn't make sense anymore. if (!cssSyntaxSelect.options[cssSyntaxSelect.options.length-1].value) { cssSyntaxSelect.options.length -= 1; } // Get the CSS for the selected theme. Utils.getLocalFile( Utils.getLocalURL('/common/highlightjs/styles/'+selected), 'text', css => { cssSyntaxEdit.value = css; }); } function loadChangelist() { Utils.getLocalFile( Utils.getLocalURL('/common/CHANGES.md'), 'text', function(changes) { var markedOptions = { gfm: true, pedantic: false, sanitize: false }; changes = marked(changes, markedOptions); Utils.saferSetInnerHTML(document.getElementById('changelist'), changes); const prevVer = location.search ? location.search.match(/prevVer=([0-9\.]+)/) : null; if (prevVer) { const version = prevVer[1]; // capture group const changelist = document.getElementById('changelist'); const allH2s = changelist.querySelectorAll('h2'); let prevVerStart = null; for (const h2 of allH2s) { if (h2.textContent.match(new RegExp('v'+version+'$'))) { prevVerStart = h2; break; } } const firstH1 = changelist.querySelector('h1:first-child'); if (firstH1) { // Create and insert the new h2 const newH2 = document.createElement('h2'); newH2.textContent = Utils.getMessage('new_changelist_items'); firstH1.insertAdjacentElement('afterend', newH2); // Collect elements between newH2 and prevVerStart const wrapper = document.createElement('div'); wrapper.className = 'changelist-new'; let current = newH2.nextElementSibling; while (current && current !== prevVerStart) { const next = current.nextElementSibling; wrapper.appendChild(current); current = next; } newH2.insertAdjacentElement('afterend', wrapper); } // Move the changelist section up in the page const changelistContainer = document.getElementById('changelist-container'); const pagehead = document.getElementById('pagehead'); pagehead.insertAdjacentElement('afterend', changelistContainer); } }); } // Choose one of the donate pleas to use, and update the donate info so we can // A/B test them. function showDonatePlea() { const pleas = document.querySelectorAll('.donate-plea'); const choice = Math.floor(Math.random() * pleas.length); const plea = pleas[choice]; const pleaId = plea.id; const submitType = plea.dataset.submitType; const paypalSubmitImage = document.getElementById('paypal-submit-image'); const paypalSubmitCss = document.getElementById('paypal-submit-css'); if (paypalSubmitImage && paypalSubmitCss) { if (submitType === 'paypal-submit-image') { paypalSubmitImage.style.display = ''; paypalSubmitCss.style.display = 'none'; } else { paypalSubmitImage.style.display = 'none'; paypalSubmitCss.style.display = ''; } } plea.classList.remove('donate-plea-hidden'); const itemNumberInput = document.querySelector('#donate-button input[name="item_number"]'); if (itemNumberInput) { itemNumberInput.value = 'options-page-' + pleaId; } } // Reset the math img tag template to default. function resetMathEdit() { mathEdit.value = OptionsStore.defaults['math-value']; } document.getElementById('math-reset-button').addEventListener('click', resetMathEdit, false); // Handle forgot-to-render checkbox changes async function handleForgotToRenderChange(event) { const isThunderbird = navigator.userAgent.indexOf('Thunderbird') !== -1; const origins = isThunderbird ? ['chrome://messenger/content/messengercompose/*'] // TODO: figure out if this is right -- it's probably not an "origin" : ['https://mail.google.com/']; if (event.target.checked) { // We're enabling forgot-to-render, so request permissions const granted = await ContentPermissions.requestPermission(origins); if (!granted) { // Permission denied - uncheck the checkbox forgotToRenderCheckEnabled.checked = false; // checkChange will pick up this change and save it } } else { // User is disabling forgot-to-render - remove permissions const removed = await ContentPermissions.removePermissions(origins); if (!removed) { console.error('Failed to remove permissions'); } } }
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
false
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/common/mdh-html-to-text.js
src/common/mdh-html-to-text.js
/* * Copyright Adam Pritchard 2015 * MIT License : https://adampritchard.mit-license.org/ */ /* This module encapsulates Markdown Here's HTML-to-plaintext functionality. */ ;(function() { "use strict"; /*global module:false, htmlToText:false, Utils:false*/ var exports = {}; /* NOTE: Maybe it would be better to process the DOM directly? String-processing the HTML seems suboptimal. */ /* `checkingIfMarkdown` should be true if the caller just wants to know if the HTML contains Markdown. It will prevent any alterations that introduce MD that isn't already present. */ function MdhHtmlToText(elem, range, checkingIfMarkdown) { this.elem = elem; this.range = range; this.checkingIfMarkdown = checkingIfMarkdown; // NOTE: If we end up really using `range`, we should do this: // if (!this.range) { this.range = new Range(); this.range.selectNodeContents(elem); } // ...or just make it non-optional. // Is this insufficient? What if `elem` is in an iframe with no `src`? // Maybe we should go higher in the iframe chain? this.url = Utils.getTopURL(elem.ownerDocument.defaultView); this._preprocess(); } /* We need to tweak the html-to-text processing to get the results we want. We also want to exclude some stuff (like reply blocks) from any processing. Returns an object that looks like this: { html: the HTML to render, exclusions: [array of { placeholder: the string added as placeholder for the excluded content content: the excluded content }] } NOTE: Maybe it would be better to do this stuff in markdown-here.js, where we have the DOM available? String-processing the HTML seems suboptimal. */ MdhHtmlToText.prototype._preprocess = function() { /* Historical note: At one time we kept lot of stuff intact: <b>, <i>, <font>, <span>-with-style-attr, <h1>, and so on. This was nice, because it let users do some rich-edit-control formatting that would be retained when rendering. But it was a pain to get/keep working properly in Yahoo mail, and it introduced issue #18. So I tore out the feature, and now we only keep a few probably-not-problematic tags. */ /* preprocessInfo ends up looking like this: { html: the HTML to render, exclusions: [array of { placeholder: the string added as placeholder for the excluded content content: the excluded content }] } */ var html; if (this.range) { html = Utils.getDocumentFragmentHTML(this.range.cloneContents()); } else { html = this.elem.innerHTML; } this.preprocessInfo = { html: html, exclusions: [] }; // The default behaviour for `jsHtmlToText.js` is to strip out tags (and their // inner text/html) that it doesn't expect/want. But we want some tag blocks // to remain intact. this.excludeTagBlocks('blockquote', true); // Try to leave intact the line that Gmail adds that says: // On such-a-date, such-a-person <email addy> wrote: this.preprocessInfo.html = this.preprocessInfo.html.replace( /&lt;<a (href="mailto:[^>]+)>([^<]*)<\/a>&gt;/ig, '&lt;&lt;a $1&gt;$2&lt;\/a&gt;&gt;'); // It's a deviation from Markdown, but we'd like to leave any rendered // images already in the email intact. So we'll escape their tags. // Note that we can't use excludeTagBlocks because there's no closing tag. this.preprocessInfo.html = this.preprocessInfo.html.replace(/<(img[^>]*)>/ig, '&lt;$1&gt;'); // Yahoo seems to often/always/sometimes (only in Chrome?) use <p> instead // of <div>. We'll replace the former with the latter so that our other rules work. // This also seems to be the case in Blogger. // Instead of adding URL matches, we're going to count the number of <p> and // <br> elements and do some replacement if there are more of the former than // the latter. var brMatches = this.preprocessInfo.html.match(/<br\b/g); brMatches = (brMatches ? brMatches.length : 0); var pMatches = this.preprocessInfo.html.match(/<p\b/g); pMatches = (pMatches ? pMatches.length : 0); if (pMatches > brMatches) { this.preprocessInfo.html = this.preprocessInfo.html .replace(/<p\b[^>]*>/ig, '<div>') .replace(/<\/p\b[^>]*>/ig, '</div>'); } if (this.checkingIfMarkdown) { // If we're just checking for Markdown, strip out `<code>` blocks so that // we don't incorrectly detect unrendered MD in them. this.preprocessInfo.html = this.preprocessInfo.html.replace(/<code\b.+?<\/code>/ig, ''); } else { // Some tags we can convert to Markdown, but don't do it if we're just // checking for Markdown, otherwise we'll cause false positives. this.preprocessInfo.html = convertHTMLtoMarkdown('a', this.preprocessInfo.html); } // NOTE: Don't use '.' in these regexes and hope to match across newlines. Instead use [\s\S]. // Experimentation has shown some tags that need to be tweaked a little. this.preprocessInfo.html = this.preprocessInfo.html // A raw text node without an enclosing <div> won't be handled properly, so enclose them. // At the beginning: .replace(/^((?:(?!<div\b)[\s\S])+)/i, '<div>$1</div>') // In the middle: .replace(/(<\/div>)((?!<div\b)[\s\S]+?)(<div\b[^>]*>)/ig, '$1<div>$2</div>$3') // At the end: // Note: The original, simpler form of this regex -- `([^>]+)$/` was // horribly slow. The new form is fast for both positive and negative // matches. I can't pretend to entirely understand why. // More info: https://stackoverflow.com/questions/31952381/end-of-string-regex-match-too-slow .replace(/^(?=([\s\S]*>))\1([^>]+)$/, '$1<div>$2</div>') // empty <div> between other <div> elems gets removed .replace(/(<\/div>)<div\b[^>]*><\/div>(<div[^>]*>)/ig, '$1$2') // <div><br></div> --> <br> .replace(/<div\b[^>]*><br\b[^>]*><\/div>/ig, '<br>') // A <br> as the last child of a <div> adds no whitespace, so: <br></div> --> </div> // Note: I can't find a reference for this, but testing shows it. // The reason we're testing for this is because we see it in the wild. E.g., issue #251. .replace(/<br\b[^>]*><\/div>/ig, '</div>') // closing </div> --> <br> (but nested </div></div> just gets one <br>) .replace(/(<\/div>)+/ig, '<br>') // open <div> --> nothing (since we've replaced all the closing tags) .replace(/<div\b[^>]*>/ig, '') // <img> tags --> textual <img> tags .replace(/<(img[^>]*)>/ig, '&lt;$1&gt;') // &nbsp; --> space .replace(/&nbsp;/ig, ' '); }; MdhHtmlToText.prototype.get = function() { return htmlToText(this.preprocessInfo.html, { allowTrailingWhitespace: true }); }; // Re-insert the excluded content that we removed in preprocessing MdhHtmlToText.prototype.postprocess = function(renderedMarkdown) { var i; for (i = 0; i < this.preprocessInfo.exclusions.length; i++) { renderedMarkdown = renderedMarkdown.replace(this.preprocessInfo.exclusions[i].placeholder, this.preprocessInfo.exclusions[i].content); } return renderedMarkdown; }; // Escape all tags between tags of type `tagName`, inclusive. Also add a // special "exclude" class to them. // If `wrapInPara` is true, `<p>` tags will be added before and after each // tag block found. // If `ifHasAttribute` is non-null, tags will only be matched if they have // that attribute. // If `ifNotHasString` is non-null, tags that contain that string will not // be matched. Note that `ifNotHasString` will be used in a regex. // TODO: This function is pretty flawed. Wrapping block elements in paras // doesn't make much sense. And if we're going to support inline // elements, then we can't unconditionally put linebreaks around the // the wrapped elements. MdhHtmlToText.prototype.excludeTagBlocks = function( tagName, wrapInPara, ifHasAttribute, ifNotHasString) { var depth, startIndex, openIndex, closeIndex, currentOpenIndex, openTagRegex, closeTagRegex, remainder, closeTagLength, regexFiller; regexFiller = ifNotHasString ? '(((?!'+ifNotHasString+')[^>])*)' : '[^>]*'; if (ifHasAttribute) { openTagRegex = new RegExp('<'+tagName+'\\b'+regexFiller+'\\b'+ifHasAttribute+'\\b'+regexFiller+'>', 'i'); } else { openTagRegex = new RegExp('<'+tagName+'\\b'+regexFiller+'>', 'i'); } closeTagRegex = new RegExp('</'+tagName+'\\b', 'i'); depth = 0; startIndex = 0; while (true) { remainder = this.preprocessInfo.html.slice(startIndex); openIndex = remainder.search(openTagRegex); closeIndex = remainder.search(closeTagRegex); if (openIndex < 0 && closeIndex < 0) { break; } if (closeIndex < 0 || (openIndex >= 0 && openIndex < closeIndex)) { // Process an open tag next. // Make the index relative to the beginning of the string. openIndex += startIndex; if (depth === 0) { // Not a nested tag. Start the escape here. currentOpenIndex = openIndex; } startIndex = openIndex + 1; depth += 1; } else { // Process a close tag next. if (depth > 0) { // Make the index relative to the beginning of the string. closeIndex += startIndex; if (depth === 1) { // Not a nested tag. Time to escape. // Because we've mangled the opening and closing tags, we need to // put around them so that they don't get mashed together with the // preceeding and following Markdown. closeTagLength = ('</'+tagName+'>').length; var placeholder = String(Math.random()); this.preprocessInfo.exclusions.push({ placeholder: placeholder, content: '<div class="markdown-here-exclude">' + (wrapInPara ? '<p>' : '') + this.preprocessInfo.html.slice(currentOpenIndex, closeIndex+closeTagLength) + (wrapInPara ? '</p>' : '') + '</div>' }); // We need to insert some empty lines when we extract something, // otherwise the stuff above and below would be rendered as if they // were together. this.preprocessInfo.html = this.preprocessInfo.html.slice(0, currentOpenIndex) + '<br><br><br>' + // three empty lines is "guaranteed" to break a Markdown block (like a bullet list) placeholder + '<br><br><br>' + this.preprocessInfo.html.slice(closeIndex+closeTagLength); // Start from the beginning again. The length of the string has // changed (so our indexes are meaningless), and we'll only find // unescaped/unprocessed tags of interest anyway. startIndex = 0; } else { startIndex = closeIndex + 1; } depth -= 1; } else { // Depth is 0. So we've found a closing tag while not in an opening // tag -- this can happen normally if `ifHasAttribute` is non-null. // Just advance the startIndex. startIndex += closeIndex + 1; } } } }; /** Converts instances of `tag` in `html` to Markdown and returns the resulting HTML. */ function convertHTMLtoMarkdown(tag, html) { if (tag === 'a') { var htmlToRestore = []; html = html.replace(/(`+)[\s\S]+?\1/ig, function($0) { var replacement = Math.random(); htmlToRestore.push([replacement, $0]); return replacement; }); /* Make sure we do *not* convert HTML links that are inside of MD links. Otherwise we'll have problems like issue #69. We're going to use a regex that mimics a negative lookbehind. For details see: https://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript Here's an attempt at an explanation of the regex: ( // begin optional prefix capture group (?:\]\([^\)]*) // match an unclosed URL portion of a MD link -- like "...](..." |(?:\[[^\]]*) // match an unclosed name portion of a MD link -- like "...[..." |(?:\[.*\]:.*) // match the patterns of reflink and nolink -- link "[...]:..." )? // capture group is optional so that we do the "negative" lookbehind -- that is, we can match links that are *not* preceded by the stuff we *don't* want <a\s[^>]*href="([^"]*)"[^>]*>(.*?)<\/a> // an HTML link Then the replace callback looks like this: return $1 ? $0 : '['+$3+']('+$2+')' So, if the first capture group is matched (i.e., $1 has value), then we've matched the bad thing -- the indication that the HTML is inside a MD link. In that case, we don't modify anything. Otherwise we use our other capture groups to create the desired MD link. */ html = html.replace( /((?:\]\([^\)]*)|(?:\[[^\]]*)|(?:\[.*\]:.*))?<a\s[^>]*href="([^"]*)"[^>]*>(.*?)<\/a>/ig, function($0, $1, $2, $3) { return $1 ? $0 : '['+$3+']('+$2+')'; }); for (var i = 0; i < htmlToRestore.length; i++) { html = html.replace(htmlToRestore[i][0], function() { // The replacement argument to `String.replace()` has some magic values: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter // Because we don't control the content of that argument, we either // need to escape dollar signs in it, or use the function version. return htmlToRestore[i][1]; }); } } else { throw new Error('convertHTMLtoMarkdown: ' + tag + ' is not a supported tag'); } return html; } exports.MdhHtmlToText = MdhHtmlToText; exports._testExports = { convertHTMLtoMarkdown: convertHTMLtoMarkdown }; var EXPORTED_SYMBOLS = ['MdhHtmlToText']; if (typeof module !== 'undefined') { module.exports = exports; } else { this.MdhHtmlToText = exports; this.EXPORTED_SYMBOLS = EXPORTED_SYMBOLS; } }).call(function() { return this || (typeof window !== 'undefined' ? window : global); }());
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
false
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/common/markdown-render.js
src/common/markdown-render.js
/* * Copyright Adam Pritchard 2013 * MIT License : https://adampritchard.mit-license.org/ */ /* * The function that does the basic raw-Markdown-in-HTML to rendered-HTML * conversion. * The reason we keep this function -- specifically, the function that uses our * external markdown renderer (marked.js), text-from-HTML module (jsHtmlToText.js), * and CSS -- separate is that it allows us to keep the bulk of the rendering * code (and the bulk of the code in our extension) out of the content script. * That way, we minimize the amount of code that needs to be loaded in every page. */ ;(function() { "use strict"; /*global module:false*/ var MarkdownRender = {}; /** Using the functionality provided by the functions htmlToText and markdownToHtml, render html into pretty text. */ function markdownRender(mdText, userprefs, marked, hljs) { function mathify(mathcode) { return userprefs['math-value'] .replace(/\{mathcode\}/ig, mathcode) .replace(/\{urlmathcode\}/ig, encodeURIComponent(mathcode)); } // Hook into some of Marked's renderer customizations var markedRenderer = new marked.Renderer(); var sanitizeLinkForAnchor = function(text) { return text.toLowerCase().replace(/[^\w]+/g, '-'); }; var defaultHeadingRenderer = markedRenderer.heading; markedRenderer.heading = function (text, level, raw) { if (userprefs['header-anchors-enabled']) { // Add an anchor right above the heading. See MDH issue #93. var sanitizedText = sanitizeLinkForAnchor(text); var anchorLink = '<a href="#" name="' + sanitizedText + '"></a>'; return '<h' + level + '>' + anchorLink + text + '</h' + level + '>\n'; } else { return defaultHeadingRenderer.call(this, text, level, raw); } }; var defaultLinkRenderer = markedRenderer.link; markedRenderer.link = function(href, title, text) { // Added to fix MDH issue #57: MD links should automatically add scheme. // Note that the presence of a ':' is used to indicate a scheme, so port // numbers will defeat this. href = href.replace(/^(?!#)([^:]+)$/, 'https://$1'); if (userprefs['header-anchors-enabled']) { // Add an anchor right above the heading. See MDH issue #93. if (href.indexOf('#') === 0) { href = '#' + sanitizeLinkForAnchor(href.slice(1).toLowerCase()); } } return defaultLinkRenderer.call(this, href, title, text); }; var markedOptions = { renderer: markedRenderer, gfm: true, pedantic: false, sanitize: false, tables: true, smartLists: true, breaks: userprefs['gfm-line-breaks-enabled'], smartypants: true, // Bit of a hack: highlight.js uses a `hljs` class to style the code block, // so we'll add it by sneaking it into this config field. langPrefix: 'hljs language-', math: userprefs['math-enabled'] ? mathify : null, highlight: function(codeText, codeLanguage) { if (codeLanguage && hljs.getLanguage(codeLanguage.toLowerCase())) { return hljs.highlight(codeText, {language: codeLanguage.toLowerCase(), ignoreIllegals: true}).value; } return codeText; } }; var renderedMarkdown = marked(mdText, markedOptions); return renderedMarkdown; } // Expose these functions MarkdownRender.markdownRender = markdownRender; var EXPORTED_SYMBOLS = ['MarkdownRender']; if (typeof module !== 'undefined') { module.exports = MarkdownRender; } else { this.MarkdownRender = MarkdownRender; this.EXPORTED_SYMBOLS = EXPORTED_SYMBOLS; } }).call(function() { return this || (typeof window !== 'undefined' ? window : global); }());
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
false
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/common/content-permissions.js
src/common/content-permissions.js
/* * Copyright Adam Pritchard 2025 * MIT License : http://adampritchard.mit-license.org/ */ /* * Content Permissions - Handles dynamic permission requests */ // TODO: Is this just too thin a wrapper around chrome.permissions to bother? 'use strict'; const ContentPermissions = { // Note that the "origin" and "origins" parameters are URLs or URL patterns. // They _require_ at least a trailing slash -- they must not be a bare domain. async hasPermission(origin) { try { // Test explicitly for http or https scheme. // If we proceed with the code below on a `moz-extension://` URL (like // our options page in Firefox), it will throw an error. if (!/^https?:\/\/.+/.test(origin)) { console.warn('Permission check skipped for non-http(s) origin:', origin); return false; } return await chrome.permissions.contains({ origins: [origin] }); } catch (e) { console.error('Error checking permission:', e); return false; } }, async requestPermission(origins) { try { return await chrome.permissions.request({ origins: origins }); } catch (e) { console.error('Error requesting permission:', e); return false; } }, async removePermissions(origins) { try { return await chrome.permissions.remove({ origins: origins }); } catch (e) { console.error('Error removing permission:', e); return false; } }, }; // Export for use in other scripts if (typeof module !== 'undefined' && module.exports) { module.exports = ContentPermissions; }
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
false
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/common/marked.js
src/common/marked.js
/** * marked - a markdown parser * Copyright (c) 2011-2013, Christopher Jeffrey. (MIT Licensed) * https://github.com/chjj/marked */ ;(function() { /** * Block-Level Grammar */ var block = { newline: /^\n+/, code: /^( {4}[^\n]+\n*)+/, fences: noop, hr: /^( *[-*_]){3,} *(?:\n+|$)/, heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/, nptable: noop, lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/, blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/, list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/, html: /^ *(?:comment|closed|closing) *(?:\n{2,}|\s*$)/, def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/, table: noop, paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/, text: /^[^\n]+/ }; block.bullet = /(?:[*+-]|\d+\.)/; block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/; block.item = replace(block.item, 'gm') (/bull/g, block.bullet) (); block.list = replace(block.list) (/bull/g, block.bullet) ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))') ('def', '\\n+(?=' + block.def.source + ')') (); block.blockquote = replace(block.blockquote) ('def', block.def) (); block._tag = '(?!(?:' + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code' + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo' + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b'; block.html = replace(block.html) ('comment', /<!--[\s\S]*?-->/) ('closed', /<(tag)[\s\S]+?<\/\1>/) ('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/) (/tag/g, block._tag) (); block.paragraph = replace(block.paragraph) ('hr', block.hr) ('heading', block.heading) ('lheading', block.lheading) ('blockquote', block.blockquote) ('tag', '<' + block._tag) ('def', block.def) (); /** * Normal Block Grammar */ block.normal = merge({}, block); /** * GFM Block Grammar */ block.gfm = merge({}, block.normal, { fences: /^ *(`{3,}|~{3,}) *(\S+)? *\n([\s\S]+?)\s*\1 *(?:\n+|$)/, paragraph: /^/ }); block.gfm.paragraph = replace(block.paragraph) ('(?!', '(?!' + block.gfm.fences.source.replace('\\1', '\\2') + '|' + block.list.source.replace('\\1', '\\3') + '|') (); /** * GFM + Tables Block Grammar */ block.tables = merge({}, block.gfm, { nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/, table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/ }); /** * Block Lexer */ function Lexer(options) { this.tokens = []; this.tokens.links = {}; this.options = options || marked.defaults; this.rules = block.normal; if (this.options.gfm) { if (this.options.tables) { this.rules = block.tables; } else { this.rules = block.gfm; } } } /** * Expose Block Rules */ Lexer.rules = block; /** * Static Lex Method */ Lexer.lex = function(src, options) { var lexer = new Lexer(options); return lexer.lex(src); }; /** * Preprocessing */ Lexer.prototype.lex = function(src) { src = src .replace(/\r\n|\r/g, '\n') .replace(/\t/g, ' ') .replace(/\u00a0/g, ' ') .replace(/\u2424/g, '\n'); return this.token(src, true); }; /** * Lexing */ Lexer.prototype.token = function(src, top, bq) { var src = src.replace(/^ +$/gm, '') , next , loose , cap , bull , b , item , space , i , l; while (src) { // newline if (cap = this.rules.newline.exec(src)) { src = src.substring(cap[0].length); if (cap[0].length > 1) { this.tokens.push({ type: 'space' }); } } // code if (cap = this.rules.code.exec(src)) { src = src.substring(cap[0].length); cap = cap[0].replace(/^ {4}/gm, ''); this.tokens.push({ type: 'code', text: !this.options.pedantic ? cap.replace(/\n+$/, '') : cap }); continue; } // fences (gfm) if (cap = this.rules.fences.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: 'code', lang: cap[2], text: cap[3] }); continue; } // heading if (cap = this.rules.heading.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: 'heading', depth: cap[1].length, text: cap[2] }); continue; } // table no leading pipe (gfm) if (top && (cap = this.rules.nptable.exec(src))) { src = src.substring(cap[0].length); item = { type: 'table', header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */), align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), cells: cap[3].replace(/\n$/, '').split('\n') }; for (i = 0; i < item.align.length; i++) { if (/^ *-+: *$/.test(item.align[i])) { item.align[i] = 'right'; } else if (/^ *:-+: *$/.test(item.align[i])) { item.align[i] = 'center'; } else if (/^ *:-+ *$/.test(item.align[i])) { item.align[i] = 'left'; } else { item.align[i] = null; } } for (i = 0; i < item.cells.length; i++) { item.cells[i] = item.cells[i].split(/ *\| */); } this.tokens.push(item); continue; } // lheading if (cap = this.rules.lheading.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: 'heading', depth: cap[2] === '=' ? 1 : 2, text: cap[1] }); continue; } // hr if (cap = this.rules.hr.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: 'hr' }); continue; } // blockquote if (cap = this.rules.blockquote.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: 'blockquote_start' }); cap = cap[0].replace(/^ *> ?/gm, ''); // Pass `top` to keep the current // "toplevel" state. This is exactly // how markdown.pl works. this.token(cap, top, true); this.tokens.push({ type: 'blockquote_end' }); continue; } // list if (cap = this.rules.list.exec(src)) { src = src.substring(cap[0].length); bull = cap[2]; this.tokens.push({ type: 'list_start', ordered: bull.length > 1 }); // Get each top-level item. cap = cap[0].match(this.rules.item); next = false; l = cap.length; i = 0; for (; i < l; i++) { item = cap[i]; // Remove the list item's bullet // so it is seen as the next token. space = item.length; item = item.replace(/^ *([*+-]|\d+\.) +/, ''); // Outdent whatever the // list item contains. Hacky. if (~item.indexOf('\n ')) { space -= item.length; item = !this.options.pedantic ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '') : item.replace(/^ {1,4}/gm, ''); } // Determine whether the next list item belongs here. // Backpedal if it does not belong in this list. if (this.options.smartLists && i !== l - 1) { b = block.bullet.exec(cap[i + 1])[0]; if (bull !== b && !(bull.length > 1 && b.length > 1)) { src = cap.slice(i + 1).join('\n') + src; i = l - 1; } } // Determine whether item is loose or not. // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/ // for discount behavior. loose = next || /\n\n(?!\s*$)/.test(item); if (i !== l - 1) { next = item.charAt(item.length - 1) === '\n'; if (!loose) loose = next; } this.tokens.push({ type: loose ? 'loose_item_start' : 'list_item_start' }); // Recurse. this.token(item, false, bq); this.tokens.push({ type: 'list_item_end' }); } this.tokens.push({ type: 'list_end' }); continue; } // html if (cap = this.rules.html.exec(src)) { src = src.substring(cap[0].length); this.tokens.push({ type: this.options.sanitize ? 'paragraph' : 'html', pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style', text: cap[0] }); continue; } // def if ((!bq && top) && (cap = this.rules.def.exec(src))) { src = src.substring(cap[0].length); this.tokens.links[cap[1].toLowerCase()] = { href: cap[2], title: cap[3] }; continue; } // table (gfm) if (top && (cap = this.rules.table.exec(src))) { src = src.substring(cap[0].length); item = { type: 'table', header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */), align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n') }; for (i = 0; i < item.align.length; i++) { if (/^ *-+: *$/.test(item.align[i])) { item.align[i] = 'right'; } else if (/^ *:-+: *$/.test(item.align[i])) { item.align[i] = 'center'; } else if (/^ *:-+ *$/.test(item.align[i])) { item.align[i] = 'left'; } else { item.align[i] = null; } } for (i = 0; i < item.cells.length; i++) { item.cells[i] = item.cells[i] .replace(/^ *\| *| *\| *$/g, '') .split(/ *\| */); } this.tokens.push(item); continue; } // top-level paragraph if (top && (cap = this.rules.paragraph.exec(src))) { src = src.substring(cap[0].length); this.tokens.push({ type: 'paragraph', text: cap[1].charAt(cap[1].length - 1) === '\n' ? cap[1].slice(0, -1) : cap[1] }); continue; } // text if (cap = this.rules.text.exec(src)) { // Top-level should never reach here. src = src.substring(cap[0].length); this.tokens.push({ type: 'text', text: cap[0] }); continue; } if (src) { throw new Error('Infinite loop on byte: ' + src.charCodeAt(0)); } } return this.tokens; }; /** * Inline-Level Grammar */ var inline = { escape: /^\\([\\`*{}\[\]()#+\-.!_>\$])/, /* adam-p: added \$ for math support */ autolink: /^<([^ >]+(@|:\/)[^ >]+)>/, url: noop, tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/, link: /^!?\[(inside)\]\(href\)/, reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/, math: /^\$([^ \t\n\$]([^\$]*[^ \t\n\$])?)\$/, /* adam-p: added for math support */ nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/, strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/, em: /^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/, code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/, br: /^ {2,}\n(?!\s*$)/, del: noop, text: /^[\s\S]+?(?=[\$\\<!\[_*`]| {2,}\n|$)/ /* adam-p: added \$ for math support */ }; inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/; inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/; inline.link = replace(inline.link) ('inside', inline._inside) ('href', inline._href) (); inline.reflink = replace(inline.reflink) ('inside', inline._inside) (); /** * Normal Inline Grammar */ inline.normal = merge({}, inline); /** * Pedantic Inline Grammar */ inline.pedantic = merge({}, inline.normal, { math: noop, /* adam-p: added for math support */ strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/, em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/ }); /** * GFM Inline Grammar */ inline.gfm = merge({}, inline.normal, { escape: replace(inline.escape)('])', '~|])')(), url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/, del: /^~~(?=\S)([\s\S]*?\S)~~/, text: replace(inline.text) (']|', '~]|') ('|', '|https?://|') () }); /** * GFM + Line Breaks Inline Grammar */ inline.breaks = merge({}, inline.gfm, { br: replace(inline.br)('{2,}', '*')(), text: replace(inline.gfm.text)('{2,}', '*')() }); /** * Inline Lexer & Compiler */ function InlineLexer(links, options) { this.options = options || marked.defaults; this.links = links; this.rules = inline.normal; this.renderer = this.options.renderer || new Renderer; this.renderer.options = this.options; if (!this.links) { throw new Error('Tokens array requires a `links` property.'); } if (this.options.gfm) { if (this.options.breaks) { this.rules = inline.breaks; } else { this.rules = inline.gfm; } } else if (this.options.pedantic) { this.rules = inline.pedantic; } } /** * Expose Inline Rules */ InlineLexer.rules = inline; /** * Static Lexing/Compiling Method */ InlineLexer.output = function(src, links, options) { var inline = new InlineLexer(links, options); return inline.output(src); }; /** * Lexing/Compiling */ InlineLexer.prototype.output = function(src) { var out = '' , link , text , href , cap; while (src) { // escape if (cap = this.rules.escape.exec(src)) { src = src.substring(cap[0].length); out += cap[1]; continue; } /* adam-p: added math support */ // math if (this.options.math && (cap = this.rules.math.exec(src))) { src = src.substring(cap[0].length); out += this.options.math(cap[1]); continue; } // autolink if (cap = this.rules.autolink.exec(src)) { src = src.substring(cap[0].length); if (cap[2] === '@') { text = cap[1].charAt(6) === ':' ? this.mangle(cap[1].substring(7)) : this.mangle(cap[1]); href = this.mangle('mailto:') + text; } else { text = escape(cap[1]); href = text; } out += this.renderer.link(href, null, text); continue; } // url (gfm) if (!this.inLink && (cap = this.rules.url.exec(src))) { src = src.substring(cap[0].length); text = escape(cap[1]); href = text; out += this.renderer.link(href, null, text); continue; } // tag if (cap = this.rules.tag.exec(src)) { if (!this.inLink && /^<a /i.test(cap[0])) { this.inLink = true; } else if (this.inLink && /^<\/a>/i.test(cap[0])) { this.inLink = false; } src = src.substring(cap[0].length); out += this.options.sanitize ? escape(cap[0]) : cap[0]; continue; } // link if (cap = this.rules.link.exec(src)) { src = src.substring(cap[0].length); this.inLink = true; out += this.outputLink(cap, { href: cap[2], title: cap[3] }); this.inLink = false; continue; } // reflink, nolink if ((cap = this.rules.reflink.exec(src)) || (cap = this.rules.nolink.exec(src))) { src = src.substring(cap[0].length); link = (cap[2] || cap[1]).replace(/\s+/g, ' '); link = this.links[link.toLowerCase()]; if (!link || !link.href) { out += cap[0].charAt(0); src = cap[0].substring(1) + src; continue; } this.inLink = true; out += this.outputLink(cap, link); this.inLink = false; continue; } // strong if (cap = this.rules.strong.exec(src)) { src = src.substring(cap[0].length); out += this.renderer.strong(this.output(cap[2] || cap[1])); continue; } // em if (cap = this.rules.em.exec(src)) { src = src.substring(cap[0].length); out += this.renderer.em(this.output(cap[2] || cap[1])); continue; } // code if (cap = this.rules.code.exec(src)) { src = src.substring(cap[0].length); out += this.renderer.codespan(escape(cap[2], true)); continue; } // br if (cap = this.rules.br.exec(src)) { src = src.substring(cap[0].length); out += this.renderer.br(); continue; } // del (gfm) if (cap = this.rules.del.exec(src)) { src = src.substring(cap[0].length); out += this.renderer.del(this.output(cap[1])); continue; } // text if (cap = this.rules.text.exec(src)) { src = src.substring(cap[0].length); out += escape(this.smartypants(cap[0])); continue; } if (src) { throw new Error('Infinite loop on byte: ' + src.charCodeAt(0)); } } return out; }; /** * Compile Link */ InlineLexer.prototype.outputLink = function(cap, link) { var href = escape(link.href) , title = link.title ? escape(link.title) : null; return cap[0].charAt(0) !== '!' ? this.renderer.link(href, title, this.output(cap[1])) : this.renderer.image(href, title, escape(cap[1])); }; /** * Smartypants Transformations */ InlineLexer.prototype.smartypants = function(text) { if (!this.options.smartypants) return text; return text /* adam-p: Adding some smart arrows */ .replace(/<-->/g, '\u2194') .replace(/<--/g, '\u2190') .replace(/-->/g, '\u2192') .replace(/<==>/g, '\u21d4') .replace(/<==/g, '\u21d0') .replace(/==>/g, '\u21d2') // em-dashes .replace(/--/g, '\u2014') // opening singles .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018') // closing singles & apostrophes .replace(/'/g, '\u2019') // opening doubles .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c') // closing doubles .replace(/"/g, '\u201d') // ellipses .replace(/\.{3}/g, '\u2026'); }; /** * Mangle Links */ InlineLexer.prototype.mangle = function(text) { var out = '' , l = text.length , i = 0 , ch; for (; i < l; i++) { ch = text.charCodeAt(i); if (Math.random() > 0.5) { ch = 'x' + ch.toString(16); } out += '&#' + ch + ';'; } return out; }; /** * Renderer */ function Renderer(options) { this.options = options || {}; } Renderer.prototype.code = function(code, lang, escaped) { if (this.options.highlight) { var out = this.options.highlight(code, lang); if (out != null && out !== code) { escaped = true; code = out; } } if (!lang) { return '<pre><code>' + (escaped ? code : escape(code, true)) + '\n</code></pre>'; } return '<pre><code class="' + this.options.langPrefix + escape(lang, true) + '">' + (escaped ? code : escape(code, true)) + '\n</code></pre>\n'; }; Renderer.prototype.blockquote = function(quote) { return '<blockquote>\n' + quote + '</blockquote>\n'; }; Renderer.prototype.html = function(html) { return html; }; Renderer.prototype.heading = function(text, level, raw) { return '<h' + level + ' id="' + this.options.headerPrefix + raw.toLowerCase().replace(/[^\w]+/g, '-') + '">' + text + '</h' + level + '>\n'; }; Renderer.prototype.hr = function() { return this.options.xhtml ? '<hr/>\n' : '<hr>\n'; }; Renderer.prototype.list = function(body, ordered) { var type = ordered ? 'ol' : 'ul'; return '<' + type + '>\n' + body + '</' + type + '>\n'; }; Renderer.prototype.listitem = function(text) { return '<li>' + text + '</li>\n'; }; Renderer.prototype.paragraph = function(text) { return '<p>' + text + '</p>\n'; }; Renderer.prototype.table = function(header, body) { return '<table>\n' + '<thead>\n' + header + '</thead>\n' + '<tbody>\n' + body + '</tbody>\n' + '</table>\n'; }; Renderer.prototype.tablerow = function(content) { return '<tr>\n' + content + '</tr>\n'; }; Renderer.prototype.tablecell = function(content, flags) { var type = flags.header ? 'th' : 'td'; var tag = flags.align ? '<' + type + ' style="text-align:' + flags.align + '">' : '<' + type + '>'; return tag + content + '</' + type + '>\n'; }; // span level renderer Renderer.prototype.strong = function(text) { return '<strong>' + text + '</strong>'; }; Renderer.prototype.em = function(text) { return '<em>' + text + '</em>'; }; Renderer.prototype.codespan = function(text) { return '<code>' + text + '</code>'; }; Renderer.prototype.br = function() { return this.options.xhtml ? '<br/>' : '<br>'; }; Renderer.prototype.del = function(text) { return '<del>' + text + '</del>'; }; Renderer.prototype.link = function(href, title, text) { if (this.options.sanitize) { try { var prot = decodeURIComponent(unescape(href)) .replace(/[^\w:]/g, '') .toLowerCase(); } catch (e) { return ''; } if (prot.indexOf('javascript:') === 0) { return ''; } } var out = '<a href="' + href + '"'; if (title) { out += ' title="' + title + '"'; } out += '>' + text + '</a>'; return out; }; Renderer.prototype.image = function(href, title, text) { var out = '<img src="' + href + '" alt="' + text + '"'; if (title) { out += ' title="' + title + '"'; } out += this.options.xhtml ? '/>' : '>'; return out; }; /** * Parsing & Compiling */ function Parser(options) { this.tokens = []; this.token = null; this.options = options || marked.defaults; this.options.renderer = this.options.renderer || new Renderer; this.renderer = this.options.renderer; this.renderer.options = this.options; } /** * Static Parse Method */ Parser.parse = function(src, options, renderer) { var parser = new Parser(options, renderer); return parser.parse(src); }; /** * Parse Loop */ Parser.prototype.parse = function(src) { this.inline = new InlineLexer(src.links, this.options, this.renderer); this.tokens = src.reverse(); var out = ''; while (this.next()) { out += this.tok(); } return out; }; /** * Next Token */ Parser.prototype.next = function() { return this.token = this.tokens.pop(); }; /** * Preview Next Token */ Parser.prototype.peek = function() { return this.tokens[this.tokens.length - 1] || 0; }; /** * Parse Text Tokens */ Parser.prototype.parseText = function() { var body = this.token.text; while (this.peek().type === 'text') { body += '\n' + this.next().text; } return this.inline.output(body); }; /** * Parse Current Token */ Parser.prototype.tok = function() { switch (this.token.type) { case 'space': { return ''; } case 'hr': { return this.renderer.hr(); } case 'heading': { return this.renderer.heading( this.inline.output(this.token.text), this.token.depth, this.token.text); } case 'code': { return this.renderer.code(this.token.text, this.token.lang, this.token.escaped); } case 'table': { var header = '' , body = '' , i , row , cell , flags , j; // header cell = ''; for (i = 0; i < this.token.header.length; i++) { flags = { header: true, align: this.token.align[i] }; cell += this.renderer.tablecell( this.inline.output(this.token.header[i]), { header: true, align: this.token.align[i] } ); } header += this.renderer.tablerow(cell); for (i = 0; i < this.token.cells.length; i++) { row = this.token.cells[i]; cell = ''; for (j = 0; j < row.length; j++) { cell += this.renderer.tablecell( this.inline.output(row[j]), { header: false, align: this.token.align[j] } ); } body += this.renderer.tablerow(cell); } return this.renderer.table(header, body); } case 'blockquote_start': { var body = ''; while (this.next().type !== 'blockquote_end') { body += this.tok(); } return this.renderer.blockquote(body); } case 'list_start': { var body = '' , ordered = this.token.ordered; while (this.next().type !== 'list_end') { body += this.tok(); } return this.renderer.list(body, ordered); } case 'list_item_start': { var body = ''; while (this.next().type !== 'list_item_end') { body += this.token.type === 'text' ? this.parseText() : this.tok(); } return this.renderer.listitem(body); } case 'loose_item_start': { var body = ''; while (this.next().type !== 'list_item_end') { body += this.tok(); } return this.renderer.listitem(body); } case 'html': { var html = !this.token.pre && !this.options.pedantic ? this.inline.output(this.token.text) : this.token.text; return this.renderer.html(html); } case 'paragraph': { return this.renderer.paragraph(this.inline.output(this.token.text)); } case 'text': { return this.renderer.paragraph(this.parseText()); } } }; /** * Helpers */ function escape(html, encode) { return html .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;'); } function unescape(html) { return html.replace(/&([#\w]+);/g, function(_, n) { n = n.toLowerCase(); if (n === 'colon') return ':'; if (n.charAt(0) === '#') { return n.charAt(1) === 'x' ? String.fromCharCode(parseInt(n.substring(2), 16)) : String.fromCharCode(+n.substring(1)); } return ''; }); } function replace(regex, opt) { regex = regex.source; opt = opt || ''; return function self(name, val) { if (!name) return new RegExp(regex, opt); val = val.source || val; val = val.replace(/(^|[^\[])\^/g, '$1'); regex = regex.replace(name, val); return self; }; } function noop() {} noop.exec = noop; function merge(obj) { var i = 1 , target , key; for (; i < arguments.length; i++) { target = arguments[i]; for (key in target) { if (Object.prototype.hasOwnProperty.call(target, key)) { obj[key] = target[key]; } } } return obj; } /** * Marked */ function marked(src, opt, callback) { if (callback || typeof opt === 'function') { if (!callback) { callback = opt; opt = null; } opt = merge({}, marked.defaults, opt || {}); var highlight = opt.highlight , tokens , pending , i = 0; try { tokens = Lexer.lex(src, opt) } catch (e) { return callback(e); } pending = tokens.length; var done = function() { var out, err; try { out = Parser.parse(tokens, opt); } catch (e) { err = e; } opt.highlight = highlight; return err ? callback(err) : callback(null, out); }; if (!highlight || highlight.length < 3) { return done(); } delete opt.highlight; if (!pending) return done(); for (; i < tokens.length; i++) { (function(token) { if (token.type !== 'code') { return --pending || done(); } return highlight(token.text, token.lang, function(err, code) { if (code == null || code === token.text) { return --pending || done(); } token.text = code; token.escaped = true; --pending || done(); }); })(tokens[i]); } return; } try { if (opt) opt = merge({}, marked.defaults, opt); return Parser.parse(Lexer.lex(src, opt), opt); } catch (e) { e.message += '\nPlease report this to https://github.com/chjj/marked.'; if ((opt || marked.defaults).silent) { return '<p>An error occured:</p><pre>' + escape(e.message + '', true) + '</pre>'; } throw e; } } /** * Options */ marked.options = marked.setOptions = function(opt) { merge(marked.defaults, opt); return marked; }; marked.defaults = { gfm: true, tables: true, breaks: false, pedantic: false, sanitize: false, smartLists: false, silent: false, highlight: null, langPrefix: 'lang-', smartypants: false, headerPrefix: '', renderer: new Renderer, xhtml: false }; /** * Expose */ marked.Parser = Parser; marked.parser = Parser.parse; marked.Renderer = Renderer; marked.Lexer = Lexer; marked.lexer = Lexer.lex; marked.InlineLexer = InlineLexer; marked.inlineLexer = InlineLexer.output; marked.parse = marked; if (typeof exports === 'object') { module.exports = marked; } else if (typeof define === 'function' && define.amd) { define(function() { return marked; }); } else { this.marked = marked; this.EXPORTED_SYMBOLS = ['marked']; /* adam-p: added easier loading in Firefox */ } }).call(function() { return this || (typeof window !== 'undefined' ? window : global); }());
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
false
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/common/options-store.js
src/common/options-store.js
/* * Copyright Adam Pritchard 2015 * MIT License : https://adampritchard.mit-license.org/ */ ;(function() { "use strict"; /*global module:false, chrome:false, Components:false*/ // Common defaults const DEFAULTS = { 'math-enabled': false, 'math-value': '<img src="https://latex.codecogs.com/png.image?\\dpi{120}\\inline&space;{urlmathcode}" alt="{mathcode}">', // When we switched to the new permissions model, we needed users to re-enable the // forgot-to-render check, so that they would be prompted to give permission to access // mail.google.com. So the name of this option changed to force that. 'forgot-to-render-check-enabled-2': false, 'header-anchors-enabled': false, 'gfm-line-breaks-enabled': true }; /* * Chrome storage helper. Gets around the synchronized value size limit. * Overall quota limits still apply (or less, but we should stay well within). * Limitations: * - `get` gets the entire options object and `set` sets the entire options * object (unlike the underlying `chrome.storage.sync` functions). * * Long strings are broken into pieces and stored in separate fields. They are * recombined when retrieved. * * Note that we fall back to (unsynced) localStorage if chrome.storage isn't * available. This is the case in Chromium v18 (currently the latest available * via Ubuntu repo). Part of the reason we JSON-encode values is to get around * the fact that you can only store strings with localStorage. * * Chrome note/warning: OptionsStore can't be used directly from a content script. * When it tries to fill in the CSS defaults with a XHR request, it'll fail with * a cross-domain restriction error. Instead use the service provided by the * background script. */ // TODO: Check for errors. See: https://code.google.com/chrome/extensions/dev/storage.html var ChromeOptionsStore = { // The options object will be passed to `callback` get: function(callback) { var that = this; this._storageGet(function(sync) { // Process the object, recombining divided entries. var tempobj = {}, finalobj = {}; for (var key in sync) { var val = sync[key]; var divIndex = key.indexOf(that._div); if (divIndex < 0) { finalobj[key] = val; } else { var keybase = key.slice(0, divIndex); var keynum = key.slice(divIndex+that._div.length); tempobj[keybase] = tempobj[keybase] || []; tempobj[keybase][keynum] = val; } } // Recombine the divided entries. for (key in tempobj) { finalobj[key] = tempobj[key].join(''); } that._fillDefaults(finalobj, callback); }); }, // Store `obj`, splitting long strings when necessary. `callback` will be // called (with no arguments) when complete. set: function(obj, callback) { var that = this; // First clear out existing entries. this._clearExisting(obj, function() { // Split long string entries into pieces, so we don't exceed the limit. var finalobj = {}; for (var key in obj) { var val = obj[key]; if (typeof(val) !== 'string' || val.length < that._maxlen()) { // Don't need to split, or can't. finalobj[key] = val; } else { var pieces = Math.ceil(val.length / that._maxlen()); for (var i = 0; i < pieces; i++) { finalobj[key+that._div+i] = val.substr(i*that._maxlen(), that._maxlen()); } } } that._storageSet(finalobj, function() { if (callback) callback(); }); }); }, remove: function(arrayOfKeys, callback) { var that = this; if (typeof(arrayOfKeys) === 'string') { arrayOfKeys = [arrayOfKeys]; } this._clearExisting(arrayOfKeys, callback); }, // The default values or URLs for our various options. defaults: { 'main-css': {'__defaultFromFile__': '/common/default.css', '__dataType__': 'text'}, 'syntax-css': {'__defaultFromFile__': '/common/highlightjs/styles/github.css', '__dataType__': 'text'}, 'math-enabled': DEFAULTS['math-enabled'], 'math-value': DEFAULTS['math-value'], 'forgot-to-render-check-enabled-2': DEFAULTS['forgot-to-render-check-enabled-2'], 'header-anchors-enabled': DEFAULTS['header-anchors-enabled'], 'gfm-line-breaks-enabled': DEFAULTS['gfm-line-breaks-enabled'] }, // Stored string pieces look like: {'key##0': 'the quick ', 'key##1': 'brown fox'} _div: '##', // HACK: Using the full length, or length-keylength, gives quota error. // Because _maxlen: function() { // Note that chrome.storage.sync.QUOTA_BYTES_PER_ITEM is in bytes, but JavaScript // strings are UTF-16, so we need to divide by 2. // Some JS string info: https://rosettacode.org/wiki/String_length#JavaScript if (chrome.storage && chrome.storage.sync && chrome.storage.sync.QUOTA_BYTES_PER_ITEM) { return chrome.storage.sync.QUOTA_BYTES_PER_ITEM / 2; } else { // 8192 is the default value for chrome.storage.sync.QUOTA_BYTES_PER_ITEM, so... return 8192 / 2; } }, _storageGet: function(callback) { if (chrome.storage) { (chrome.storage.sync || chrome.storage.local).get(null, function(obj) { var key; for (key in obj) { // Older settings aren't JSON-encoded, so they'll throw an exception. try { obj[key] = JSON.parse(obj[key]); } catch (ex) { // do nothing, leave the value as-is } } callback(obj); }); return; } else { // Make this actually an async call. Utils.nextTick(function() { var i, obj = {}; for (i = 0; i < localStorage.length; i++) { // Older settings aren't JSON-encoded, so they'll throw an exception. try { obj[localStorage.key(i)] = JSON.parse(localStorage.getItem(localStorage.key(i))); } catch (ex) { obj[localStorage.key(i)] = localStorage.getItem(localStorage.key(i)); } } callback(obj); }); return; } }, _storageSet: function(obj, callback) { var key, finalobj = {}; for (key in obj) { finalobj[key] = JSON.stringify(obj[key]); } if (chrome.storage) { (chrome.storage.sync || chrome.storage.local).set(finalobj, callback); return; } else { // Make this actually an async call. Utils.nextTick(function() { var key; for (key in finalobj) { localStorage.setItem(key, finalobj[key]); } if (callback) callback(); }); return; } }, _storageRemove: function(keysToDelete, callback) { if (chrome.storage) { (chrome.storage.sync || chrome.storage.local).remove(keysToDelete, callback); return; } else { // Make this actually an async call. Utils.nextTick(function() { var i; for (i = 0; i < keysToDelete.length; i++) { localStorage.removeItem(keysToDelete[i]); } callback(); }); return; } }, // Clear any existing entries that match the given object's members. _clearExisting: function(obj, callback) { var that = this, newObj = {}, i; if (obj.constructor === Array) { newObj = {}; for (i = 0; i < obj.length; i++) { newObj[obj[i]] = null; } obj = newObj; } this._storageGet(function(sync) { var keysToDelete = []; for (var objKey in obj) { for (var syncKey in sync) { if (syncKey === objKey || syncKey.indexOf(objKey+that._div) === 0) { keysToDelete.push(syncKey); } } } if (keysToDelete.length > 0) { that._storageRemove(keysToDelete, callback); } else { if (callback) callback(); } }); } }; // Use ChromeOptionsStore for all WebExtensions platforms this.OptionsStore = ChromeOptionsStore; this.OptionsStore._fillDefaults = function(prefsObj, callback) { var that = this; // Upgrade the object, if necessary. // Motivation: Our default for the LaTeX renderer used to be Google Charts API. Google // discontinued the service and we switched the default to CodeCogs, but because it was // the default, it will be set in many users' OptionsStore. We need to forcibly replace it. if (typeof prefsObj['math-value'] === 'string' && prefsObj['math-value'].indexOf('chart.googleapis.com') >= 0) { prefsObj['math-value'] = that.defaults['math-value']; } var key, allKeys = []; for (key in that.defaults) { if (that.defaults.hasOwnProperty(key)) { allKeys.push(key); } } doNextKey(); function doNextKey() { if (allKeys.length === 0) { // All done. // Ensure this function is actually asynchronous. Utils.nextTick(function() { callback(prefsObj); }); return; } // Keep processing keys (and recurse) doDefaultForKey(allKeys.pop(), doNextKey); } // This function may be asynchronous (if XHR occurs) or it may be a straight // synchronous callback invocation. function doDefaultForKey(key, callback) { // Only take action if the key doesn't already have a value set. if (typeof(prefsObj[key]) === 'undefined') { if (that.defaults[key].hasOwnProperty('__defaultFromFile__')) { Utils.getLocalFile( that.defaults[key]['__defaultFromFile__'], that.defaults[key]['__dataType__'] || 'text', function(data) { prefsObj[key] = data; callback(); }); return; } else { // Set the default. prefsObj[key] = that.defaults[key]; // Recurse callback(); return; } } else { // Key already has a value -- skip it. callback(); return; } } }; var EXPORTED_SYMBOLS = ['OptionsStore']; this.EXPORTED_SYMBOLS = EXPORTED_SYMBOLS; }).call(function() { return this || (typeof window !== 'undefined' ? window : global); }());
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
false
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/common/utils.js
src/common/utils.js
/* * Copyright Adam Pritchard 2015 * MIT License : https://adampritchard.mit-license.org/ */ /* * Utilities and helpers that are needed in multiple places. * * This module assumes that a global `window` is available. */ ;(function() { "use strict"; /*global module:false, chrome:false*/ function consoleLog(logString) { if (typeof(console) !== 'undefined') { console.log(logString); } } // TODO: Try to use `insertAdjacentHTML` for the inner and outer HTML functions. // https://developer.mozilla.org/en-US/docs/Web/API/Element.insertAdjacentHTML /** * Safely parse an HTML string into a DocumentFragment without executing scripts. * Uses DOMPurify to sanitize and parse HTML into a DocumentFragment. * * @param {string} htmlString - The HTML string to parse and sanitize. * @param {Document} [ownerDocument] - The document to use for creating the fragment. Defaults to the global document. * @param {boolean} [allowStyleTags] - Whether to allow <style> tags in the sanitized output. * @returns {DocumentFragment} The sanitized DocumentFragment. */ function safelyParseHTML(htmlString, ownerDocument, allowStyleTags=false) { ownerDocument = ownerDocument || document; // DOMPurify is required for security if (typeof DOMPurify === 'undefined') { throw new Error('DOMPurify is required but not loaded. Cannot safely parse HTML.'); } const domPurifyConfig = { RETURN_DOM_FRAGMENT: true, // Return a DocumentFragment instead of a string DOCUMENT: ownerDocument, // Specify which document to use for creating the fragment }; if (allowStyleTags) { domPurifyConfig.ADD_TAGS = ['style']; // Allow <style> tags domPurifyConfig.FORCE_BODY = true; // Ensure <style> tags are processed correctly } // Sanitize and parse HTML into a DocumentFragment const docFrag = DOMPurify.sanitize(htmlString, domPurifyConfig); return docFrag; } // Assigning a string directly to `element.innerHTML` is potentially dangerous: // e.g., the string can contain harmful script elements. (Additionally, Mozilla // won't let us pass validation with `innerHTML` assignments in place.) // This function provides a safer way to append a HTML string into an element. function saferSetInnerHTML(parentElem, htmlString, allowStyleTags=false) { const docFrag = safelyParseHTML(htmlString, parentElem.ownerDocument, allowStyleTags); const range = parentElem.ownerDocument.createRange(); range.selectNodeContents(parentElem); range.deleteContents(); range.insertNode(docFrag); range.detach(); } // Approximately equivalent to assigning to `outerHTML` -- completely replaces // the target element with `htmlString`. // Note that some caveats apply that also apply to `outerHTML`: // - The element must be in the DOM. Otherwise an exception will be thrown. // - The original element has been removed from the DOM, but continues to exist. // Any references to it (such as the one passed into this function) will be // references to the original. function saferSetOuterHTML(elem, htmlString, allowStyleTags=false) { if (!isElementInDocument(elem)) { throw new Error('Element must be in document'); } const docFrag = safelyParseHTML(htmlString, elem.ownerDocument, allowStyleTags); const range = elem.ownerDocument.createRange(); range.selectNode(elem); range.deleteContents(); range.insertNode(docFrag); range.detach(); } // Walk the DOM, executing `func` on each element. // From Crockford. function walkDOM(node, func) { func(node); node = node.firstChild; while(node) { walkDOM(node, func); node = node.nextSibling; } } // Next three functions from: https://stackoverflow.com/a/1483487/729729 // Returns true if `node` is in `range`. function rangeIntersectsNode(range, node) { var nodeRange; // adam-p: I have found that Range.intersectsNode gives incorrect results in // Chrome (but not Firefox). So we're going to use the fail-back code always, // regardless of whether the current platform implements Range.intersectsNode. /* if (range.intersectsNode) { return range.intersectsNode(node); } else { ... */ nodeRange = node.ownerDocument.createRange(); try { nodeRange.selectNode(node); } catch (e) { nodeRange.selectNodeContents(node); } // TODO: Remove this workaround, as we no longer support Postbox or XUL Mozilla. // Workaround for this old Mozilla bug, which is still present in Postbox: // https://bugzilla.mozilla.org/show_bug.cgi?id=665279 var END_TO_START = node.ownerDocument.defaultView.Range.END_TO_START || window.Range.END_TO_START; var START_TO_END = node.ownerDocument.defaultView.Range.START_TO_END || window.Range.START_TO_END; return range.compareBoundaryPoints( END_TO_START, nodeRange) === -1 && range.compareBoundaryPoints( START_TO_END, nodeRange) === 1; } // Returns array of elements in selection. function getSelectedElementsInDocument(doc) { var range, sel, containerElement; sel = doc.getSelection(); if (sel.rangeCount > 0) { range = sel.getRangeAt(0); } if (!range) { return []; } return getSelectedElementsInRange(range); } // Returns array of elements in range function getSelectedElementsInRange(range) { var elems = [], treeWalker, containerElement; if (range) { containerElement = range.commonAncestorContainer; if (containerElement.nodeType != 1) { containerElement = containerElement.parentNode; } elems = [treeWalker.currentNode]; walkDOM( containerElement, function(node) { if (rangeIntersectsNode(range, node)) { elems.push(node); } }); /*? if(platform!=='firefox'){ */ /* // This code is probably superior, but TreeWalker is not supported by Postbox. // If this ends up getting used, it should probably be moved into walkDOM // (or walkDOM should be removed). treeWalker = doc.createTreeWalker( containerElement, range.commonAncestorContainerownerDocument.defaultView.NodeFilter.SHOW_ELEMENT, function(node) { return rangeIntersectsNode(range, node) ? range.commonAncestorContainerownerDocument.defaultView.NodeFilter.FILTER_ACCEPT : range.commonAncestorContainerownerDocument.defaultView.NodeFilter.FILTER_REJECT; }, false ); elems = [treeWalker.currentNode]; while (treeWalker.nextNode()) { elems.push(treeWalker.currentNode); } */ /*? } */ } return elems; } function isElementInDocument(element) { var doc = element.ownerDocument; while (!!(element = element.parentNode)) { if (element === doc) { return true; } } return false; } // From: https://stackoverflow.com/a/3819589/729729 // Postbox doesn't support `node.outerHTML`. function outerHTML(node, doc) { // if IE, Chrome take the internal method otherwise build one return node.outerHTML || ( function(n){ var div = doc.createElement('div'), h; div.appendChild(n.cloneNode(true)); h = div.innerHTML; div = null; return h; })(node); } // From: https://stackoverflow.com/a/5499821/729729 var charsToReplace = { '&': '&amp;', '<': '&lt;', '>': '&gt;' }; function replaceChar(char) { return charsToReplace[char] || char; } // An approximate equivalent to outerHTML for document fragments. function getDocumentFragmentHTML(docFrag) { var html = '', i; for (i = 0; i < docFrag.childNodes.length; i++) { var node = docFrag.childNodes[i]; if (node.nodeType === node.TEXT_NODE) { html += node.nodeValue.replace(/[&<>]/g, replaceChar); } else { // going to assume ELEMENT_NODE html += outerHTML(node, docFrag.ownerDocument); } } return html; } function isElementDescendant(parent, descendant) { var ancestor = descendant; while (!!(ancestor = ancestor.parentNode)) { if (ancestor === parent) { return true; } } return false; } // Take a URL that refers to a file in this extension and makes it absolute. // Note that the URL *must not* be relative to the current path position (i.e., // no "./blah" or "../blah"). So `url` must start with `/`. function getLocalURL(url) { if (url[0] !== '/') { throw 'relative url not allowed: ' + url; } if (url.indexOf('://') >= 0) { // already absolute return url; } return chrome.runtime.getURL(url); } // Makes an asynchronous XHR request for a local file (basically a thin wrapper). // `dataType` must be one of 'text', 'json', or 'base64'. // `callback` will be called with the response value, of a type depending on `dataType`. // Errors are not expected for local files, and will result in an exception being thrown asynchronously. // TODO: Return a promise instead of using a callback. This will allow returning an error // properly, and then this can be used in options.js when checking for the existence of // the test file. function getLocalFile(url, dataType, callback) { fetch(url) .then(response => { if (!response.ok) { throw new Error(`HTTP error status: ${response.status}`); } switch (dataType) { case 'text': return response.text(); case 'json': return response.json(); case 'base64': return response.blob(); default: throw new Error(`Unknown dataType: ${dataType}`); } }) .then(data => { switch (dataType) { case 'text': case 'json': callback(data); break; case 'base64': data.arrayBuffer().then(function(buffer) { var uInt8Array = new Uint8Array(buffer); var base64Data = base64EncArr(uInt8Array); callback(base64Data); }); } }) .catch(err => { throw new Error(`Error fetching local file: ${url}: ${err}`); }); } // Events fired by Markdown Here will have this property set to true. var MARKDOWN_HERE_EVENT = 'markdown-here-event'; // Fire a mouse event on the given element. (Note: not super robust.) function fireMouseClick(elem) { var clickEvent = elem.ownerDocument.createEvent('MouseEvent'); clickEvent.initMouseEvent( 'click', true, // bubbles: We want the event to bubble. true, // cancelable elem.ownerDocument.defaultView, // view, 1, // detail, 0, // screenX 0, // screenY 0, // clientX 0, // clientY false, // ctrlKey false, // altKey false, // shiftKey false, // metaKey 0, // button null); // relatedTarget clickEvent[MARKDOWN_HERE_EVENT] = true; elem.dispatchEvent(clickEvent); } var PRIVILEGED_REQUEST_EVENT_NAME = 'markdown-here-request-event'; function makeRequestToPrivilegedScript(doc, requestObj, callback) { // If `callback` is undefined and we pass it anyway, Chrome complains with this: // Uncaught Error: Invocation of form extension.sendMessage(object, undefined, null) doesn't match definition extension.sendMessage(optional string extensionId, any message, optional function responseCallback) if (callback) { chrome.runtime.sendMessage(requestObj, callback); } else { chrome.runtime.sendMessage(requestObj); } } // Gives focus to the element. // Setting focus into elements inside iframes is not simple. function setFocus(elem) { // We need to do some tail-recursion focus setting up through the iframes. if (elem.document) { // This is a window if (elem.frameElement) { // This is the window of an iframe. Set focus to the parent window. setFocus(elem.frameElement.ownerDocument.defaultView); } } else if (elem.ownerDocument.defaultView.frameElement) { // This element is in an iframe. Set focus to its owner window. setFocus(elem.ownerDocument.defaultView); } elem.focus(); } // Gets the URL of the top window that elem belongs to. // May recurse up through iframes. function getTopURL(win, justHostname) { if (win.frameElement) { // This is the window of an iframe return getTopURL(win.frameElement.ownerDocument.defaultView); } var url; // We still want a useful value if we're in Thunderbird, etc. if (!win.location.href || win.location.href === 'about:blank') { url = win.navigator.userAgent.match(/Thunderbird'/); if (url) { url = url[0]; } } else if (justHostname) { url = win.location.hostname; } else { url = win.location.href; } return url; } // Regarding methods for `nextTick` and related: // For ordinary browser use, setTimeout() is throttled to 1000ms for inactive // tabs. This doesn't seem to affect extensions, except... Chrome Canary is // currently doing this for the extension background scripts. This causes // horribly slow rendering. For info see: // https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout#Inactive_tabs // As an alternative, we can use a local XHR request/response. // This function just does a simple, local async request and then calls the callback. function asyncCallbackXHR(callback) { fetch(getLocalURL('/common/CHANGES.md'), {method: 'HEAD'}) .then(callback) .catch(callback); } function asyncCallbackTimeout(callback) { setTimeout(callback, 0); } // We prefer to use the setTimeout approach. var asyncCallback = asyncCallbackTimeout; // Sets a short timeout and then calls callback function nextTick(callback, context) { nextTickFn(callback, context)(); } // `context` is optional. Will be `this` when `callback` is called. function nextTickFn(callback, context) { var start = new Date(); return function nextTickFnInner() { var args = arguments; var runner = function() { // Detect a whether the async callback was super slow var end = new Date() - start; if (end > 200) { // setTimeout is too slow -- switch to the XHR approach. asyncCallback = asyncCallbackXHR; } callback.apply(context, args); }; asyncCallback(runner); }; } // Returns true if the semver version string in a is greater than the one in b. // If a or b isn't a version string, a simple string comparison is returned. // If a or b is falsy, false is returned. // From https://stackoverflow.com/a/55466325 function semverGreaterThan(a, b) { if (!a || !b) { return false; } return a.localeCompare(b, undefined, { numeric: true }) === 1; } /* * i18n/l10n */ // Get the translated string indicated by `messageID`. // Note that there's no support for placeholders as yet. // Throws exception if message is not found. function getMessage(messageID) { var message = chrome.i18n.getMessage(messageID); if (!message) { throw new Error('Could not find message ID: ' + messageID); } return message; } /*****************************************************************************/ /*\ |*| |*| Base64 / binary data / UTF-8 strings utilities |*| |*| https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding |*| \*/ /* Array of bytes to base64 string decoding */ function b64ToUint6 (nChr) { return nChr > 64 && nChr < 91 ? nChr - 65 : nChr > 96 && nChr < 123 ? nChr - 71 : nChr > 47 && nChr < 58 ? nChr + 4 : nChr === 43 ? 62 : nChr === 47 ? 63 : 0; } function base64DecToArr (sBase64, nBlocksSize) { var sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length, nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2, taBytes = new Uint8Array(nOutLen); for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) { nMod4 = nInIdx & 3; nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4; if (nMod4 === 3 || nInLen - nInIdx === 1) { for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) { taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255; } nUint24 = 0; } } return taBytes; } /* Base64 string to array encoding */ function uint6ToB64 (nUint6) { return nUint6 < 26 ? nUint6 + 65 : nUint6 < 52 ? nUint6 + 71 : nUint6 < 62 ? nUint6 - 4 : nUint6 === 62 ? 43 : nUint6 === 63 ? 47 : 65; } function base64EncArr (aBytes) { var nMod3 = 2, sB64Enc = ""; for (var nLen = aBytes.length, nUint24 = 0, nIdx = 0; nIdx < nLen; nIdx++) { nMod3 = nIdx % 3; if (nIdx > 0 && (nIdx * 4 / 3) % 76 === 0) { sB64Enc += "\r\n"; } nUint24 |= aBytes[nIdx] << (16 >>> nMod3 & 24); if (nMod3 === 2 || aBytes.length - nIdx === 1) { sB64Enc += String.fromCharCode(uint6ToB64(nUint24 >>> 18 & 63), uint6ToB64(nUint24 >>> 12 & 63), uint6ToB64(nUint24 >>> 6 & 63), uint6ToB64(nUint24 & 63)); nUint24 = 0; } } return sB64Enc.substr(0, sB64Enc.length - 2 + nMod3) + (nMod3 === 2 ? '' : nMod3 === 1 ? '=' : '=='); } /* UTF-8 array to DOMString and vice versa */ function utf8ArrToStr (aBytes) { var sView = ""; for (var nPart, nLen = aBytes.length, nIdx = 0; nIdx < nLen; nIdx++) { nPart = aBytes[nIdx]; sView += String.fromCharCode( nPart > 251 && nPart < 254 && nIdx + 5 < nLen ? /* six bytes */ /* (nPart - 252 << 32) is not possible in ECMAScript! So...: */ (nPart - 252) * 1073741824 + (aBytes[++nIdx] - 128 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128 : nPart > 247 && nPart < 252 && nIdx + 4 < nLen ? /* five bytes */ (nPart - 248 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128 : nPart > 239 && nPart < 248 && nIdx + 3 < nLen ? /* four bytes */ (nPart - 240 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128 : nPart > 223 && nPart < 240 && nIdx + 2 < nLen ? /* three bytes */ (nPart - 224 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128 : nPart > 191 && nPart < 224 && nIdx + 1 < nLen ? /* two bytes */ (nPart - 192 << 6) + aBytes[++nIdx] - 128 : /* nPart < 127 ? */ /* one byte */ nPart ); } return sView; } function strToUTF8Arr (sDOMStr) { var aBytes, nChr, nStrLen = sDOMStr.length, nArrLen = 0; /* mapping... */ for (var nMapIdx = 0; nMapIdx < nStrLen; nMapIdx++) { nChr = sDOMStr.charCodeAt(nMapIdx); nArrLen += nChr < 0x80 ? 1 : nChr < 0x800 ? 2 : nChr < 0x10000 ? 3 : nChr < 0x200000 ? 4 : nChr < 0x4000000 ? 5 : 6; } aBytes = new Uint8Array(nArrLen); /* transcription... */ for (var nIdx = 0, nChrIdx = 0; nIdx < nArrLen; nChrIdx++) { nChr = sDOMStr.charCodeAt(nChrIdx); if (nChr < 128) { /* one byte */ aBytes[nIdx++] = nChr; } else if (nChr < 0x800) { /* two bytes */ aBytes[nIdx++] = 192 + (nChr >>> 6); aBytes[nIdx++] = 128 + (nChr & 63); } else if (nChr < 0x10000) { /* three bytes */ aBytes[nIdx++] = 224 + (nChr >>> 12); aBytes[nIdx++] = 128 + (nChr >>> 6 & 63); aBytes[nIdx++] = 128 + (nChr & 63); } else if (nChr < 0x200000) { /* four bytes */ aBytes[nIdx++] = 240 + (nChr >>> 18); aBytes[nIdx++] = 128 + (nChr >>> 12 & 63); aBytes[nIdx++] = 128 + (nChr >>> 6 & 63); aBytes[nIdx++] = 128 + (nChr & 63); } else if (nChr < 0x4000000) { /* five bytes */ aBytes[nIdx++] = 248 + (nChr >>> 24); aBytes[nIdx++] = 128 + (nChr >>> 18 & 63); aBytes[nIdx++] = 128 + (nChr >>> 12 & 63); aBytes[nIdx++] = 128 + (nChr >>> 6 & 63); aBytes[nIdx++] = 128 + (nChr & 63); } else /* if (nChr <= 0x7fffffff) */ { /* six bytes */ aBytes[nIdx++] = 252 + /* (nChr >>> 32) is not possible in ECMAScript! So...: */ (nChr / 1073741824); aBytes[nIdx++] = 128 + (nChr >>> 24 & 63); aBytes[nIdx++] = 128 + (nChr >>> 18 & 63); aBytes[nIdx++] = 128 + (nChr >>> 12 & 63); aBytes[nIdx++] = 128 + (nChr >>> 6 & 63); aBytes[nIdx++] = 128 + (nChr & 63); } } return aBytes; } /*****************************************************************************/ function utf8StringToBase64(str) { return base64EncArr(strToUTF8Arr(str)); } function base64ToUTF8String(str) { return utf8ArrToStr(base64DecToArr(str)); } // Expose these functions var Utils = {}; Utils.saferSetInnerHTML = saferSetInnerHTML; Utils.saferSetOuterHTML = saferSetOuterHTML; Utils.safelyParseHTML = safelyParseHTML; Utils.walkDOM = walkDOM; Utils.rangeIntersectsNode = rangeIntersectsNode; Utils.getDocumentFragmentHTML = getDocumentFragmentHTML; Utils.isElementDescendant = isElementDescendant; Utils.getLocalURL = getLocalURL; Utils.getLocalFile = getLocalFile; Utils.fireMouseClick = fireMouseClick; Utils.MARKDOWN_HERE_EVENT = MARKDOWN_HERE_EVENT; Utils.makeRequestToPrivilegedScript = makeRequestToPrivilegedScript; Utils.PRIVILEGED_REQUEST_EVENT_NAME = PRIVILEGED_REQUEST_EVENT_NAME; Utils.consoleLog = consoleLog; Utils.setFocus = setFocus; Utils.getTopURL = getTopURL; Utils.nextTick = nextTick; Utils.nextTickFn = nextTickFn; Utils.getMessage = getMessage; Utils.semverGreaterThan = semverGreaterThan; Utils.utf8StringToBase64 = utf8StringToBase64; Utils.base64ToUTF8String = base64ToUTF8String; var EXPORTED_SYMBOLS = ['Utils']; if (typeof module !== 'undefined') { module.exports = Utils; } else { this.Utils = Utils; this.EXPORTED_SYMBOLS = EXPORTED_SYMBOLS; } }).call(function() { return this || (typeof window !== 'undefined' ? window : global); }());
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
false
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/common/vendor/dompurify.min.js
src/common/vendor/dompurify.min.js
/*! @license DOMPurify 3.2.6 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.6/LICENSE */ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).DOMPurify=t()}(this,(function(){"use strict";const{entries:e,setPrototypeOf:t,isFrozen:n,getPrototypeOf:o,getOwnPropertyDescriptor:r}=Object;let{freeze:i,seal:a,create:l}=Object,{apply:c,construct:s}="undefined"!=typeof Reflect&&Reflect;i||(i=function(e){return e}),a||(a=function(e){return e}),c||(c=function(e,t,n){return e.apply(t,n)}),s||(s=function(e,t){return new e(...t)});const u=R(Array.prototype.forEach),m=R(Array.prototype.lastIndexOf),p=R(Array.prototype.pop),f=R(Array.prototype.push),d=R(Array.prototype.splice),h=R(String.prototype.toLowerCase),g=R(String.prototype.toString),T=R(String.prototype.match),y=R(String.prototype.replace),E=R(String.prototype.indexOf),A=R(String.prototype.trim),_=R(Object.prototype.hasOwnProperty),S=R(RegExp.prototype.test),b=(N=TypeError,function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return s(N,t)});var N;function R(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,o=new Array(n>1?n-1:0),r=1;r<n;r++)o[r-1]=arguments[r];return c(e,t,o)}}function w(e,o){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:h;t&&t(e,null);let i=o.length;for(;i--;){let t=o[i];if("string"==typeof t){const e=r(t);e!==t&&(n(o)||(o[i]=e),t=e)}e[t]=!0}return e}function O(e){for(let t=0;t<e.length;t++){_(e,t)||(e[t]=null)}return e}function D(t){const n=l(null);for(const[o,r]of e(t)){_(t,o)&&(Array.isArray(r)?n[o]=O(r):r&&"object"==typeof r&&r.constructor===Object?n[o]=D(r):n[o]=r)}return n}function v(e,t){for(;null!==e;){const n=r(e,t);if(n){if(n.get)return R(n.get);if("function"==typeof n.value)return R(n.value)}e=o(e)}return function(){return null}}const L=i(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),x=i(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","slot","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),C=i(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),k=i(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),I=i(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),M=i(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),U=i(["#text"]),z=i(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),P=i(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),H=i(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),F=i(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),B=a(/\{\{[\w\W]*|[\w\W]*\}\}/gm),W=a(/<%[\w\W]*|[\w\W]*%>/gm),G=a(/\$\{[\w\W]*/gm),Y=a(/^data-[\-\w.\u00B7-\uFFFF]+$/),j=a(/^aria-[\-\w]+$/),X=a(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),q=a(/^(?:\w+script|data):/i),$=a(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),K=a(/^html$/i),V=a(/^[a-z][.\w]*(-[.\w]+)+$/i);var Z=Object.freeze({__proto__:null,ARIA_ATTR:j,ATTR_WHITESPACE:$,CUSTOM_ELEMENT:V,DATA_ATTR:Y,DOCTYPE_NAME:K,ERB_EXPR:W,IS_ALLOWED_URI:X,IS_SCRIPT_OR_DATA:q,MUSTACHE_EXPR:B,TMPLIT_EXPR:G});const J=1,Q=3,ee=7,te=8,ne=9,oe=function(){return"undefined"==typeof window?null:window};var re=function t(){let n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:oe();const o=e=>t(e);if(o.version="3.2.6",o.removed=[],!n||!n.document||n.document.nodeType!==ne||!n.Element)return o.isSupported=!1,o;let{document:r}=n;const a=r,c=a.currentScript,{DocumentFragment:s,HTMLTemplateElement:N,Node:R,Element:O,NodeFilter:B,NamedNodeMap:W=n.NamedNodeMap||n.MozNamedAttrMap,HTMLFormElement:G,DOMParser:Y,trustedTypes:j}=n,q=O.prototype,$=v(q,"cloneNode"),V=v(q,"remove"),re=v(q,"nextSibling"),ie=v(q,"childNodes"),ae=v(q,"parentNode");if("function"==typeof N){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let le,ce="";const{implementation:se,createNodeIterator:ue,createDocumentFragment:me,getElementsByTagName:pe}=r,{importNode:fe}=a;let de={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};o.isSupported="function"==typeof e&&"function"==typeof ae&&se&&void 0!==se.createHTMLDocument;const{MUSTACHE_EXPR:he,ERB_EXPR:ge,TMPLIT_EXPR:Te,DATA_ATTR:ye,ARIA_ATTR:Ee,IS_SCRIPT_OR_DATA:Ae,ATTR_WHITESPACE:_e,CUSTOM_ELEMENT:Se}=Z;let{IS_ALLOWED_URI:be}=Z,Ne=null;const Re=w({},[...L,...x,...C,...I,...U]);let we=null;const Oe=w({},[...z,...P,...H,...F]);let De=Object.seal(l(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ve=null,Le=null,xe=!0,Ce=!0,ke=!1,Ie=!0,Me=!1,Ue=!0,ze=!1,Pe=!1,He=!1,Fe=!1,Be=!1,We=!1,Ge=!0,Ye=!1,je=!0,Xe=!1,qe={},$e=null;const Ke=w({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Ve=null;const Ze=w({},["audio","video","img","source","image","track"]);let Je=null;const Qe=w({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),et="http://www.w3.org/1998/Math/MathML",tt="http://www.w3.org/2000/svg",nt="http://www.w3.org/1999/xhtml";let ot=nt,rt=!1,it=null;const at=w({},[et,tt,nt],g);let lt=w({},["mi","mo","mn","ms","mtext"]),ct=w({},["annotation-xml"]);const st=w({},["title","style","font","a","script"]);let ut=null;const mt=["application/xhtml+xml","text/html"];let pt=null,ft=null;const dt=r.createElement("form"),ht=function(e){return e instanceof RegExp||e instanceof Function},gt=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!ft||ft!==e){if(e&&"object"==typeof e||(e={}),e=D(e),ut=-1===mt.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,pt="application/xhtml+xml"===ut?g:h,Ne=_(e,"ALLOWED_TAGS")?w({},e.ALLOWED_TAGS,pt):Re,we=_(e,"ALLOWED_ATTR")?w({},e.ALLOWED_ATTR,pt):Oe,it=_(e,"ALLOWED_NAMESPACES")?w({},e.ALLOWED_NAMESPACES,g):at,Je=_(e,"ADD_URI_SAFE_ATTR")?w(D(Qe),e.ADD_URI_SAFE_ATTR,pt):Qe,Ve=_(e,"ADD_DATA_URI_TAGS")?w(D(Ze),e.ADD_DATA_URI_TAGS,pt):Ze,$e=_(e,"FORBID_CONTENTS")?w({},e.FORBID_CONTENTS,pt):Ke,ve=_(e,"FORBID_TAGS")?w({},e.FORBID_TAGS,pt):D({}),Le=_(e,"FORBID_ATTR")?w({},e.FORBID_ATTR,pt):D({}),qe=!!_(e,"USE_PROFILES")&&e.USE_PROFILES,xe=!1!==e.ALLOW_ARIA_ATTR,Ce=!1!==e.ALLOW_DATA_ATTR,ke=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Ie=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,Me=e.SAFE_FOR_TEMPLATES||!1,Ue=!1!==e.SAFE_FOR_XML,ze=e.WHOLE_DOCUMENT||!1,Fe=e.RETURN_DOM||!1,Be=e.RETURN_DOM_FRAGMENT||!1,We=e.RETURN_TRUSTED_TYPE||!1,He=e.FORCE_BODY||!1,Ge=!1!==e.SANITIZE_DOM,Ye=e.SANITIZE_NAMED_PROPS||!1,je=!1!==e.KEEP_CONTENT,Xe=e.IN_PLACE||!1,be=e.ALLOWED_URI_REGEXP||X,ot=e.NAMESPACE||nt,lt=e.MATHML_TEXT_INTEGRATION_POINTS||lt,ct=e.HTML_INTEGRATION_POINTS||ct,De=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&ht(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(De.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&ht(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(De.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(De.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Me&&(Ce=!1),Be&&(Fe=!0),qe&&(Ne=w({},U),we=[],!0===qe.html&&(w(Ne,L),w(we,z)),!0===qe.svg&&(w(Ne,x),w(we,P),w(we,F)),!0===qe.svgFilters&&(w(Ne,C),w(we,P),w(we,F)),!0===qe.mathMl&&(w(Ne,I),w(we,H),w(we,F))),e.ADD_TAGS&&(Ne===Re&&(Ne=D(Ne)),w(Ne,e.ADD_TAGS,pt)),e.ADD_ATTR&&(we===Oe&&(we=D(we)),w(we,e.ADD_ATTR,pt)),e.ADD_URI_SAFE_ATTR&&w(Je,e.ADD_URI_SAFE_ATTR,pt),e.FORBID_CONTENTS&&($e===Ke&&($e=D($e)),w($e,e.FORBID_CONTENTS,pt)),je&&(Ne["#text"]=!0),ze&&w(Ne,["html","head","body"]),Ne.table&&(w(Ne,["tbody"]),delete ve.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw b('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw b('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');le=e.TRUSTED_TYPES_POLICY,ce=le.createHTML("")}else void 0===le&&(le=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const o="data-tt-policy-suffix";t&&t.hasAttribute(o)&&(n=t.getAttribute(o));const r="dompurify"+(n?"#"+n:"");try{return e.createPolicy(r,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+r+" could not be created."),null}}(j,c)),null!==le&&"string"==typeof ce&&(ce=le.createHTML(""));i&&i(e),ft=e}},Tt=w({},[...x,...C,...k]),yt=w({},[...I,...M]),Et=function(e){f(o.removed,{element:e});try{ae(e).removeChild(e)}catch(t){V(e)}},At=function(e,t){try{f(o.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){f(o.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(Fe||Be)try{Et(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},_t=function(e){let t=null,n=null;if(He)e="<remove></remove>"+e;else{const t=T(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===ut&&ot===nt&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const o=le?le.createHTML(e):e;if(ot===nt)try{t=(new Y).parseFromString(o,ut)}catch(e){}if(!t||!t.documentElement){t=se.createDocument(ot,"template",null);try{t.documentElement.innerHTML=rt?ce:o}catch(e){}}const i=t.body||t.documentElement;return e&&n&&i.insertBefore(r.createTextNode(n),i.childNodes[0]||null),ot===nt?pe.call(t,ze?"html":"body")[0]:ze?t.documentElement:i},St=function(e){return ue.call(e.ownerDocument||e,e,B.SHOW_ELEMENT|B.SHOW_COMMENT|B.SHOW_TEXT|B.SHOW_PROCESSING_INSTRUCTION|B.SHOW_CDATA_SECTION,null)},bt=function(e){return e instanceof G&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof W)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes)},Nt=function(e){return"function"==typeof R&&e instanceof R};function Rt(e,t,n){u(e,(e=>{e.call(o,t,n,ft)}))}const wt=function(e){let t=null;if(Rt(de.beforeSanitizeElements,e,null),bt(e))return Et(e),!0;const n=pt(e.nodeName);if(Rt(de.uponSanitizeElement,e,{tagName:n,allowedTags:Ne}),Ue&&e.hasChildNodes()&&!Nt(e.firstElementChild)&&S(/<[/\w!]/g,e.innerHTML)&&S(/<[/\w!]/g,e.textContent))return Et(e),!0;if(e.nodeType===ee)return Et(e),!0;if(Ue&&e.nodeType===te&&S(/<[/\w]/g,e.data))return Et(e),!0;if(!Ne[n]||ve[n]){if(!ve[n]&&Dt(n)){if(De.tagNameCheck instanceof RegExp&&S(De.tagNameCheck,n))return!1;if(De.tagNameCheck instanceof Function&&De.tagNameCheck(n))return!1}if(je&&!$e[n]){const t=ae(e)||e.parentNode,n=ie(e)||e.childNodes;if(n&&t){for(let o=n.length-1;o>=0;--o){const r=$(n[o],!0);r.__removalCount=(e.__removalCount||0)+1,t.insertBefore(r,re(e))}}}return Et(e),!0}return e instanceof O&&!function(e){let t=ae(e);t&&t.tagName||(t={namespaceURI:ot,tagName:"template"});const n=h(e.tagName),o=h(t.tagName);return!!it[e.namespaceURI]&&(e.namespaceURI===tt?t.namespaceURI===nt?"svg"===n:t.namespaceURI===et?"svg"===n&&("annotation-xml"===o||lt[o]):Boolean(Tt[n]):e.namespaceURI===et?t.namespaceURI===nt?"math"===n:t.namespaceURI===tt?"math"===n&&ct[o]:Boolean(yt[n]):e.namespaceURI===nt?!(t.namespaceURI===tt&&!ct[o])&&!(t.namespaceURI===et&&!lt[o])&&!yt[n]&&(st[n]||!Tt[n]):!("application/xhtml+xml"!==ut||!it[e.namespaceURI]))}(e)?(Et(e),!0):"noscript"!==n&&"noembed"!==n&&"noframes"!==n||!S(/<\/no(script|embed|frames)/i,e.innerHTML)?(Me&&e.nodeType===Q&&(t=e.textContent,u([he,ge,Te],(e=>{t=y(t,e," ")})),e.textContent!==t&&(f(o.removed,{element:e.cloneNode()}),e.textContent=t)),Rt(de.afterSanitizeElements,e,null),!1):(Et(e),!0)},Ot=function(e,t,n){if(Ge&&("id"===t||"name"===t)&&(n in r||n in dt))return!1;if(Ce&&!Le[t]&&S(ye,t));else if(xe&&S(Ee,t));else if(!we[t]||Le[t]){if(!(Dt(e)&&(De.tagNameCheck instanceof RegExp&&S(De.tagNameCheck,e)||De.tagNameCheck instanceof Function&&De.tagNameCheck(e))&&(De.attributeNameCheck instanceof RegExp&&S(De.attributeNameCheck,t)||De.attributeNameCheck instanceof Function&&De.attributeNameCheck(t,e))||"is"===t&&De.allowCustomizedBuiltInElements&&(De.tagNameCheck instanceof RegExp&&S(De.tagNameCheck,n)||De.tagNameCheck instanceof Function&&De.tagNameCheck(n))))return!1}else if(Je[t]);else if(S(be,y(n,_e,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==E(n,"data:")||!Ve[e]){if(ke&&!S(Ae,y(n,_e,"")));else if(n)return!1}else;return!0},Dt=function(e){return"annotation-xml"!==e&&T(e,Se)},vt=function(e){Rt(de.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||bt(e))return;const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:we,forceKeepAttr:void 0};let r=t.length;for(;r--;){const i=t[r],{name:a,namespaceURI:l,value:c}=i,s=pt(a),m=c;let f="value"===a?m:A(m);if(n.attrName=s,n.attrValue=f,n.keepAttr=!0,n.forceKeepAttr=void 0,Rt(de.uponSanitizeAttribute,e,n),f=n.attrValue,!Ye||"id"!==s&&"name"!==s||(At(a,e),f="user-content-"+f),Ue&&S(/((--!?|])>)|<\/(style|title)/i,f)){At(a,e);continue}if("attributename"===s&&T(f,"href")){At(a,e);continue}if(n.forceKeepAttr)continue;if(!n.keepAttr){At(a,e);continue}if(!Ie&&S(/\/>/i,f)){At(a,e);continue}Me&&u([he,ge,Te],(e=>{f=y(f,e," ")}));const d=pt(e.nodeName);if(Ot(d,s,f)){if(le&&"object"==typeof j&&"function"==typeof j.getAttributeType)if(l);else switch(j.getAttributeType(d,s)){case"TrustedHTML":f=le.createHTML(f);break;case"TrustedScriptURL":f=le.createScriptURL(f)}if(f!==m)try{l?e.setAttributeNS(l,a,f):e.setAttribute(a,f),bt(e)?Et(e):p(o.removed)}catch(t){At(a,e)}}else At(a,e)}Rt(de.afterSanitizeAttributes,e,null)},Lt=function e(t){let n=null;const o=St(t);for(Rt(de.beforeSanitizeShadowDOM,t,null);n=o.nextNode();)Rt(de.uponSanitizeShadowNode,n,null),wt(n),vt(n),n.content instanceof s&&e(n.content);Rt(de.afterSanitizeShadowDOM,t,null)};return o.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=null,r=null,i=null,l=null;if(rt=!e,rt&&(e="\x3c!--\x3e"),"string"!=typeof e&&!Nt(e)){if("function"!=typeof e.toString)throw b("toString is not a function");if("string"!=typeof(e=e.toString()))throw b("dirty is not a string, aborting")}if(!o.isSupported)return e;if(Pe||gt(t),o.removed=[],"string"==typeof e&&(Xe=!1),Xe){if(e.nodeName){const t=pt(e.nodeName);if(!Ne[t]||ve[t])throw b("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof R)n=_t("\x3c!----\x3e"),r=n.ownerDocument.importNode(e,!0),r.nodeType===J&&"BODY"===r.nodeName||"HTML"===r.nodeName?n=r:n.appendChild(r);else{if(!Fe&&!Me&&!ze&&-1===e.indexOf("<"))return le&&We?le.createHTML(e):e;if(n=_t(e),!n)return Fe?null:We?ce:""}n&&He&&Et(n.firstChild);const c=St(Xe?e:n);for(;i=c.nextNode();)wt(i),vt(i),i.content instanceof s&&Lt(i.content);if(Xe)return e;if(Fe){if(Be)for(l=me.call(n.ownerDocument);n.firstChild;)l.appendChild(n.firstChild);else l=n;return(we.shadowroot||we.shadowrootmode)&&(l=fe.call(a,l,!0)),l}let m=ze?n.outerHTML:n.innerHTML;return ze&&Ne["!doctype"]&&n.ownerDocument&&n.ownerDocument.doctype&&n.ownerDocument.doctype.name&&S(K,n.ownerDocument.doctype.name)&&(m="<!DOCTYPE "+n.ownerDocument.doctype.name+">\n"+m),Me&&u([he,ge,Te],(e=>{m=y(m,e," ")})),le&&We?le.createHTML(m):m},o.setConfig=function(){gt(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),Pe=!0},o.clearConfig=function(){ft=null,Pe=!1},o.isValidAttribute=function(e,t,n){ft||gt({});const o=pt(e),r=pt(t);return Ot(o,r,n)},o.addHook=function(e,t){"function"==typeof t&&f(de[e],t)},o.removeHook=function(e,t){if(void 0!==t){const n=m(de[e],t);return-1===n?void 0:d(de[e],n,1)[0]}return p(de[e])},o.removeHooks=function(e){de[e]=[]},o.removeAllHooks=function(){de={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},o}();return re})); //# sourceMappingURL=purify.min.js.map
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
false
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/common/test/test-run.js
src/common/test/test-run.js
/* * Copyright Adam Pritchard 2013 * MIT License : https://adampritchard.mit-license.org/ */ document.addEventListener('DOMContentLoaded', function() { mocha // I'm not sure what introduces the global "schemaTypes", but it's not // Markdown Here and it causes an error on one of my Chrome instances. .globals([ 'schemaTypes' ]) // acceptable globals .run(); });
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
false
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/common/test/mdh-html-to-text-test.js
src/common/test/mdh-html-to-text-test.js
/* * Copyright Adam Pritchard 2015 * MIT License : https://adampritchard.mit-license.org/ */ "use strict"; /* jshint curly:true, noempty:true, newcap:true, eqeqeq:true, eqnull:true, undef:true, devel:true, browser:true, node:true, evil:false, latedef:false, nonew:true, trailing:false, immed:false, smarttabs:true, expr:true */ /* global describe, expect, it, before, beforeEach, after, afterEach */ /* global _, MarkdownRender, htmlToText, marked, hljs, Utils, MdhHtmlToText */ // TODO: Test ranges. // TODO: Lots more tests. describe('MdhHtmlToText', function() { it('should exist', function() { expect(MdhHtmlToText).to.exist; expect(MdhHtmlToText.MdhHtmlToText).to.exist; }); // Wraps the normal HTML-to-text calls const get = function(mdHTML) { const elem = document.createElement('div'); Utils.saferSetInnerHTML(elem, mdHTML); document.body.appendChild(elem); const mdhHtmlToText = new MdhHtmlToText.MdhHtmlToText(elem); const text = mdhHtmlToText.get(); elem.parentNode.removeChild(elem); return text; }; // Wraps the check-for-unrendered-MD HTML-to-text calls const check = function(mdHTML) { const elem = document.createElement('div'); Utils.saferSetInnerHTML(elem, mdHTML); document.body.appendChild(elem); const mdhHtmlToText = new MdhHtmlToText.MdhHtmlToText(elem, null, true); const text = mdhHtmlToText.get(); elem.parentNode.removeChild(elem); return text; }; describe('MdhHtmlToText (normal mode)', function() { it('should be okay with an empty string', function() { expect(get('')).to.equal(''); }); // Fix for https://github.com/adam-p/markdown-here/issues/104 it('should correctly handle pre-rendered links in inline code (fix for issue #104)', function() { var html = 'aaa `<a href="bbb">ccc</a>`'; // Real target var target = 'aaa `ccc`'; expect(get(html)).to.equal(target); }); // Fix for https://github.com/adam-p/markdown-here/issues/104 it('should correctly handle pre-rendered links in code blocks (fix for issue #104)', function() { var html = '```<br><a href="aaa">bbb</a><br>```'; // Real target var target = '```\nbbb\n```'; expect(get(html)).to.equal(target); }); // Busted due to https://github.com/adam-p/markdown-here/issues/104 it('should NOT correctly handle pre-rendered links in code blocks (busted due to issue #104)', function() { var html = '&nbsp;&nbsp;&nbsp;&nbsp;<a href="aaa">bbb</a><br>'; // Real target // var target = ' bbb'; var target = ' [bbb](aaa)'; expect(get(html)).to.equal(target); }); // Test fix for bug https://github.com/adam-p/markdown-here/pull/233 // reflinks and nolinks weren't working with pre-rendered links. it('should work correctly with pre-rendered links in reflinks and nolinks', function() { // // reflinks // var html = '[link text][1]<br>[1]: <a href="http://example.com">http://example.com</a><br>'; var target = '[link text][1]\n[1]: http://example.com'; expect(get(html)).to.equal(target); // HTTPS and a target attribute html = '[link text][1]<br>[1]: <a href="https://example.com" target="_blank">https://example.com</a><br>'; target = '[link text][1]\n[1]: https://example.com'; expect(get(html)).to.equal(target); // Different URL for HREF and text of link (should use text of link) html = '[link text][1]<br>[1]: <a href="http://hreflink.com">https://textlink.com</a><br>'; target = '[link text][1]\n[1]: https://textlink.com'; expect(get(html)).to.equal(target); // Only the hostname part of the URL is a link html = '[link text][1]<br>[1]: http://<a href="http://example.com">example.com</a><br>'; target = '[link text][1]\n[1]: http://example.com'; expect(get(html)).to.equal(target); // // nolinks // html = '[link text]<br>[link text]: <a href="http://example.com">http://example.com</a><br>'; target = '[link text]\n[link text]: http://example.com'; expect(get(html)).to.equal(target); // HTTPS and a target attribute html = '[link text]<br>[link text]: <a href="https://example.com" target="_blank">https://example.com</a><br>'; target = '[link text]\n[link text]: https://example.com'; expect(get(html)).to.equal(target); // Different URL for HREF and text of link (should use text of link) html = '[link text]<br>[link text]: <a href="http://hreflink.com">https://textlink.com</a><br>'; target = '[link text]\n[link text]: https://textlink.com'; expect(get(html)).to.equal(target); // Only the hostname part of the URL is a link html = '[link text]<br>[link text]: http://<a href="http://example.com">example.com</a><br>'; target = '[link text]\n[link text]: http://example.com'; expect(get(html)).to.equal(target); }); // Test fix for bug https://github.com/adam-p/markdown-here/issues/251 // <br> at the end of <div> should not add a newline it('should not add an extra newline for br at end of div', function() { // HTML from issue var html = '<div><div>mardown | test<br>-- |---<br></div>1 |\ntest<br></div>2 | test2<br clear="all">'; var target = 'mardown | test\n-- |---\n1 | test\n2 | test2'; expect(get(html)).to.equal(target); }); // Test some cases with bare text nodes it('should properly handle bare text nodes', function() { var html = ''; var target = ''; expect(get(html)).to.equal(target); html = 'asdf'; target = 'asdf'; expect(get(html)).to.equal(target); html = 'asdf<div class="x">qwer</div>'; target = 'asdf\nqwer'; expect(get(html)).to.equal(target); html = 'asdf<br class="x">qwer'; target = 'asdf\nqwer'; expect(get(html)).to.equal(target); html = 'asdf<br class="x">qwer<div>zxcv</div>asdf'; target = 'asdf\nqwer\nzxcv\nasdf'; expect(get(html)).to.equal(target); html = 'asdf<br class="x">qwer<div>zxcv</div>ghjk<div>yuio</div>asdf'; target = 'asdf\nqwer\nzxcv\nghjk\nyuio\nasdf'; expect(get(html)).to.equal(target); html = 'asdf<br class="x">qwer<div><div>zxcv</div>ghjk<div>yuio</div></div>asdf'; target = 'asdf\nqwer\nzxcv\nghjk\nyuio\nasdf'; expect(get(html)).to.equal(target); html = 'asdf\n<br class="x">qwer<div><div>zxcv</div>ghjk<div>yuio</div></div>asdf'; target = 'asdf \nqwer\nzxcv\nghjk\nyuio\nasdf'; expect(get(html)).to.equal(target); html = '<div class="x">asdf</div>qwer'; target = 'asdf\nqwer'; expect(get(html)).to.equal(target); }); // Test the fix for bug https://github.com/adam-p/markdown-here/issues/288 // Use of dollar sign in inline code producing odd results it('should properly handle a dollar sign in inline code', function() { var html = '`$`'; var target = '`$`'; expect(get(html)).to.equal(target); }); // Test the fix for bug https://github.com/adam-p/markdown-here/issues/289 // Large HTML input caused bad slowness and hangs it('should not hang on big HTML input', function() { var html = BIG_BAD_STRING; // The times here were chosen pretty unscientifically, and will stop // ensuring failure as processors get faster. (And may fail incorrectly // on a slow machine.) // Test a no-match for the was-known-to-be-bad regex var start = new Date(); get(html); var end = new Date(); expect(end.getTime() - start.getTime()).to.be.below(1000); // Test a match for the was-known-to-be-bad regex html += 'x'; start = new Date(); get(html); end = new Date(); expect(end.getTime() - start.getTime()).to.be.below(1000); }); }); describe('MdhHtmlToText (check-for-MD mode)', function() { it('should be okay with an empty string', function() { expect(check('')).to.equal(''); }); it('should not choke on links', function() { // Links get de-rendered to MD normally, but not when checking var html = '<a href="https://markdown-here.com">MDH</a>'; var target = 'MDH'; expect(check(html)).to.equal(target); }); // Check for fix to https://github.com/adam-p/markdown-here/issues/128 it('should exclude the content of <code> elements', function() { // Because otherwise unrendered MD in code would get falsely detected. var html = 'Foo<code style="blah">inline code</code>Bar<pre style="blah"><code style="blah">code block</code></pre>Okay'; var target = 'FooBar\n\nOkay'; expect(check(html)).to.equal(target); }); }); }); var BIG_BAD_STRING = '<div><pre style="font-size:0.85em;font-family:Consolas,Inconsolata,Courier,monospace;font-size:1em;line-height:1.2em;margin:1.2em 0px"><code style="font-size:0.85em;font-family:Consolas,Inconsolata,Courier,monospace;margin:0px 0.15em;padding:0px 0.3em;white-space:pre-wrap;border:1px solid rgb(234,234,234);border-radius:3px;display:inline;background-color:rgb(248,248,248);white-space:pre-wrap;overflow:auto;border-radius:3px;border:1px solid rgb(204,204,204);padding:0.5em 0.7em;display:block!important;display:block;overflow-x:auto;padding:0.5em;color:rgb(51,51,51);background:rgb(248,248,248)"><span><span style="color:rgb(51,51,51);font-weight:bold">function</span> <span style="color:rgb(153,0,0);font-weight:bold">syntaxHighlighting</span><span>()</span> </span>{\n <span style="color:rgb(51,51,51);font-weight:bold">var</span> n = <span style="color:rgb(0,128,128)">33</span>;\n <span style="color:rgb(51,51,51);font-weight:bold">var</span> s = <span style="color:rgb(221,17,68)">"hello, こんにちは"</span>;\n <span style="color:rgb(0,134,179)">console</span>.log(s);\n}\n</code></pre>\n<ul style="margin:1.2em 0px;padding-lfet:2em">\n<li style="margin:0.5em 0px">plain</li>\n<li style="margin:0.5em 0px"><em>emphasis</em><ul style="margin:1.2em 0px;padding-left:2em;margin:0px;padding-left:1em">\n<li style="margin:0.5em 0px"><strong>strong emphasis</strong><ul style="margin:1.2em 0px;padding-left:2em;margin:0px;padding-left:1em">\n<li style="margin:0.5em 0px"><del>strikethrough</del></li>\n</ul>\n</li>\n</ul>\n</li>\n<li style="margin:0.5em 0px"><code style="font-size:0.85em;font-family:Consolas,Inconsolata,Courier,monospace;margin:0px 0.15em;padding:0px 0.3em;white-space:pre-wrap;border:1px solid rgb(234,234,234);border-radius:3px;display:inline;background-color:rgb(248,248,248)">inline code</code></li>\n</ul>\n<ol style="margin:1.2em 0px;padding-left:2em">\n<li style="margin:0.5em 0px">Numbered list<ol style="margin:1.2em 0px;padding-left:2em;margin:0px;padding-left:1em;list-style-type:lower-roman">\n<li style="margin:0.5em 0px">Numbered sub-list<ol style="margin:1.2em 0px;padding-left:2em;margin:0px;padding-left:1em;list-style-type:lower-roman;list-style-type:lower-alpha">\n<li style="margin:0.5em 0px">Numbered sub-sub-list</li>\n</ol>\n</li>\n</ol>\n</li>\n<li style="margin:0.5em 0px"><a href="https://www.google.com" target="_blank">Link</a></li>\n</ol>\n<p style="margin:0px 0px 1.2em!important">An image: <img src="https://ci6.googleusercontent.com/proxy/SnqZGOlvv1rmqrH0D3Hv3b_xgSYDF1X85eF5yiLlq7JA460-RO1EUXU3m6je9Clj3CIVzrbcfE0mNObMdllDlTyOUEWMXBY7pgk=s0-d-e1-ft#https://adam-p.github.io/markdown-here/img/icon24.png" alt="Markdown Here logo" class="CToWUd"> </p>\n<blockquote style="margin:1.2em 0px;border-left-width:4px;border-left-style:solid;border-left-color:rgb(221,221,221);padding:0px 1em;color:rgb(119,119,119);quotes:none">\n<p style="margin:0px 0px 1.2em!important">Block quote.<br><em>With</em> <strong>some</strong> <code style="font-size:0.85em;font-family:Consolas,Inconsolata,Courier,monospace;margin:0px 0.15em;padding:0px 0.3em;white-space:pre-wrap;border:1px solid rgb(234,234,234);border-radius:3px;display:inline;background-color:rgb(248,248,248)">markdown</code>.</p>\n</blockquote>\n<p style="margin:0px 0px 1.2em!important">If <strong>TeX Math</strong> support is enabled, this is the quadratic equation:<br><img src="https://ci6.googleusercontent.com/proxy/Sp3KOkAUXBpjcStpC8T3Jdqb7b8SSr1BfD2cAfBIfujneu6qK8KOq5ul5JDzCWrvUGbkcbMErHPvZbekk91jruwtGojKwnXRMwbpWqaW9XNn9YUjdl64c4P9yBIPU2uc-YfaDe8MxJDAPqX-pQVv7ycg1CELz3RzsHN-Uw=s0-d-e1-ft#https://latex.codecogs.com/png.image?\\dpi{120}\\inline&space;-b%20%5Cpm%20%5Csqrt%7Bb%5E2%20-%204ac%7D%20%5Cover%202a" alt="-b \\pm \\sqrt{b^2 - 4ac} \\over 2a" class="CToWUd"></p>\n<h1 style="margin:1.3em 0px 1em;padding:0px;font-weight:bold;font-size:1.6em;border-bottom-width:1px;border-bottom-style:solid;border-bottom-color:rgb(221,221,221)"><a href="#14f1a36fb61d8846_" name="14f1a36fb61d8846_header-1"></a>Header 1</h1>\n<h2 style="margin:1.3em 0px 1em;padding:0px;font-weight:bold;font-size:1.4em;border-bottom-width:1px;border-bottom-style:solid;border-bottom-color:rgb(238,238,238)"><a href="#14f1a36fb61d8846_" name="14f1a36fb61d8846_header-2"></a>Header 2</h2>\n<h3 style="margin:1.3em 0px 1em;padding:0px;font-weight:bold;font-size:1.3em"><a href="#14f1a36fb61d8846_" name="14f1a36fb61d8846_header-3"></a>Header 3</h3>\n<h4 style="margin:1.3em 0px 1em;padding:0px;font-weight:bold;font-size:1.2em"><a href="#14f1a36fb61d8846_" name="14f1a36fb61d8846_header-4"></a>Header 4</h4>\n<h5 style="margin:1.3em 0px 1em;padding:0px;font-weight:bold;font-size:1em"><a href="#14f1a36fb61d8846_" name="14f1a36fb61d8846_header-5"></a>Header 5</h5>\n<h6 style="margin:1.3em 0px 1em;padding:0px;font-weight:bold;font-size:1em;color:rgb(119,119,119)"><a href="#14f1a36fb61d8846_" name="14f1a36fb61d8846_header-6"></a>Header 6</h6>\n<table style="margin:1.2em 0px;padding:0px;border-collapse:collapse;border-spacing:0px;font-family:inherit;font-size:inherit;font-style:inherit;font-variant:inherit;font-weight:inherit;font-stretch:inherit;line-height:inherit;border:0px">\n<thead>\n<tr style="border-width:1px 0px 0px;border-top-style:solid;border-top-color:rgb(204,204,204);margin:0px;padding:0px;background-color:white">\n<th style="font-size:1em;border:1px solid rgb(204,204,204);margin:0px;padding:0.5em 1em;font-weight:bold;background-color:rgb(240,240,240)">Tables</th>\n<th style="text-align:center;font-size:1em;border:1px solid rgb(204,204,204);margin:0px;padding:0.5em 1em;font-weight:bold;background-color:rgb(240,240,240)">Are</th>\n<th style="text-align:right;font-size:1em;border:1px solid rgb(204,204,204);margin:0px;padding:0.5em 1em;font-weight:bold;background-color:rgb(240,240,240)">Cool</th>\n</tr>\n</thead>\n<tbody style="margin:0px;padding:0px;border:0px">\n<tr style="border-width:1px 0px 0px;border-top-style:solid;border-top-color:rgb(204,204,204);margin:0px;padding:0px;background-color:white">\n<td style="font-size:1em;border:1px solid rgb(204,204,204);margin:0px;padding:0.5em 1em">column 3 is</td>\n<td style="text-align:center;font-size:1em;border:1px solid rgb(204,204,204);margin:0px;padding:0.5em 1em">right-aligned</td>\n<td style="text-align:right;font-size:1em;border:1px solid rgb(204,204,204);margin:0px;padding:0.5em 1em">$1600</td>\n</tr>\n<tr style="border-width:1px 0px 0px;border-top-style:solid;border-top-color:rgb(204,204,204);margin:0px;padding:0px;background-color:white;background-color:rgb(248,248,248)">\n<td style="font-size:1em;border:1px solid rgb(204,204,204);margin:0px;padding:0.5em 1em">column 2 is</td>\n<td style="text-align:center;font-size:1em;border:1px solid rgb(204,204,204);margin:0px;padding:0.5em 1em">centered</td>\n<td style="text-align:right;font-size:1em;border:1px solid rgb(204,204,204);margin:0px;padding:0.5em 1em">$12</td>\n</tr>\n<tr style="border-width:1px 0px 0px;border-top-style:solid;border-top-color:rgb(204,204,204);margin:0px;padding:0px;background-color:white">\n<td style="font-size:1em;border:1px solid rgb(204,204,204);margin:0px;padding:0.5em 1em">zebra stripes</td>\n<td style="text-align:center;font-size:1em;border:1px solid rgb(204,204,204);margin:0px;padding:0.5em 1em">are neat</td>\n<td style="text-align:right;font-size:1em;border:1px solid rgb(204,204,204);margin:0px;padding:0.5em 1em">$1</td>\n</tr>\n</tbody>\n</table>\n<p style="margin:0px 0px 1.2em!important">Here’s a horizontal rule:</p>\n<hr>\n<pre style="font-size:0.85em;font-family:Consolas,Inconsolata,Courier,monospace;font-size:1em;line-height:1.2em;margin:1.2em 0px"><code style="font-size:0.85em;font-family:Consolas,Inconsolata,Courier,monospace;margin:0px 0.15em;padding:0px 0.3em;white-space:pre-wrap;border:1px solid rgb(234,234,234);border-radius:3px;display:inline;background-color:rgb(248,248,248);white-space:pre-wrap;overflow:auto;border-radius:3px;border:1px solid rgb(204,204,204);padding:0.5em 0.7em;display:block!important">code block\nwith no highlighting\n</code></pre><div title="MDH:PGRpdj5gYGBqYXZhc2NyaXB0PC9kaXY+PGRpdj5mdW5jdGlvbiBzeW50YXhIaWdobGlnaHRpbmco\nKSB7PC9kaXY+PGRpdj4mbmJzcDsgdmFyIG4gPSAzMzs8L2Rpdj48ZGl2PiZuYnNwOyB2YXIgcyA9\nICJoZWxsbywg44GT44KT44Gr44Gh44GvIjs8L2Rpdj48ZGl2PiZuYnNwOyBjb25zb2xlLmxvZyhz\nKTs8L2Rpdj48ZGl2Pn08L2Rpdj48ZGl2PmBgYDwvZGl2PjxkaXY+PGJyPjwvZGl2PjxkaXY+KiBw\nbGFpbjwvZGl2PjxkaXY+KiAqZW1waGFzaXMqPC9kaXY+PGRpdj4mbmJzcDsgKiAqKnN0cm9uZyBl\nbXBoYXNpcyoqPC9kaXY+PGRpdj4mbmJzcDsgJm5ic3A7ICogfn5zdHJpa2V0aHJvdWdofn48L2Rp\ndj48ZGl2PiogYGlubGluZSBjb2RlYDwvZGl2PjxkaXY+PGJyPjwvZGl2PjxkaXY+MS4gTnVtYmVy\nZWQgbGlzdDwvZGl2PjxkaXY+Jm5ic3A7ICZuYnNwOzEuIE51bWJlcmVkIHN1Yi1saXN0PC9kaXY+\nPGRpdj4mbmJzcDsgJm5ic3A7ICZuYnNwOyAxLiBOdW1iZXJlZCBzdWItc3ViLWxpc3Q8L2Rpdj48\nZGl2PjIuIFtMaW5rXShodHRwczovL3d3dy5nb29nbGUuY29tKTwvZGl2PjxkaXY+PGJyPjwvZGl2\nPjxkaXY+PGJyPjwvZGl2PjxkaXY+QW4gaW1hZ2U6ICFbTWFya2Rvd24gSGVyZSBsb2dvXShodHRw\nOi8vYWRhbS1wLmdpdGh1Yi5pby9tYXJrZG93bi1oZXJlL2ltZy9pY29uMjQucG5nKSZuYnNwOzwv\nZGl2PjxkaXY+PGJyPjwvZGl2PjxkaXY+Jmd0OyBCbG9jayBxdW90ZS4gJm5ic3A7PC9kaXY+PGRp\ndj4mZ3Q7ICpXaXRoKiAqKnNvbWUqKiBgbWFya2Rvd25gLjwvZGl2PjxkaXY+PGJyPjwvZGl2Pjxk\naXY+SWYgKipUZVggTWF0aCoqIHN1cHBvcnQgaXMgZW5hYmxlZCwgdGhpcyBpcyB0aGUgcXVhZHJh\ndGljIGVxdWF0aW9uOiZuYnNwOzwvZGl2PjxkaXY+JC1iIFxwbSBcc3FydHtiXjIgLSA0YWN9IFxv\ndmVyIDJhJDwvZGl2PjxkaXY+PGJyPjwvZGl2PjxkaXY+IyBIZWFkZXIgMTwvZGl2PjxkaXY+IyMg\nSGVhZGVyIDI8L2Rpdj48ZGl2PiMjIyBIZWFkZXIgMzwvZGl2PjxkaXY+IyMjIyBIZWFkZXIgNDwv\nZGl2PjxkaXY+IyMjIyMgSGVhZGVyIDU8L2Rpdj48ZGl2PiMjIyMjIyBIZWFkZXIgNjwvZGl2Pjxk\naXY+Jm5ic3A7Jm5ic3A7PC9kaXY+PGRpdj58IFRhYmxlcyB8IEFyZSB8IENvb2wgfDwvZGl2Pjxk\naXY+fCAtLS0tLS0tLS0tLS0tIHw6LS0tLS0tLS0tLS0tLTp8IC0tLS0tOnw8L2Rpdj48ZGl2Pnwg\nY29sdW1uIDMgaXMgfCByaWdodC1hbGlnbmVkIHwgJDE2MDAgfDwvZGl2PjxkaXY+fCBjb2x1bW4g\nMiBpcyB8IGNlbnRlcmVkIHwgJDEyIHw8L2Rpdj48ZGl2PnwgemVicmEgc3RyaXBlcyB8IGFyZSBu\nZWF0IHwgJDEgfDwvZGl2PjxkaXY+PGJyPjwvZGl2PjxkaXY+SGVyZSdzIGEgaG9yaXpvbnRhbCBy\ndWxlOjwvZGl2PjxkaXY+PGJyPjwvZGl2PjxkaXY+LS0tPC9kaXY+PGRpdj48YnI+PC9kaXY+PGRp\ndj5gYGA8L2Rpdj48ZGl2PmNvZGUgYmxvY2s8L2Rpdj48ZGl2PndpdGggbm8gaGlnaGxpZ2h0aW5n\nPC9kaXY+PGRpdj5gYGA8L2Rpdj48ZGl2Pjxicj48L2Rpdj4=" style="min-height:0;width:0;max-height:0;max-width:0;overflow:hidden;font-size:0em;padding:0;margin:0"></div></div>' .repeat(100);
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
false
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/common/test/test-prep.js
src/common/test/test-prep.js
/* * Copyright Adam Pritchard 2013 * MIT License : https://adampritchard.mit-license.org/ */ mocha.setup('bdd'); var expect = chai.expect;
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
false
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/common/test/chai.js
src/common/test/chai.js
!function (name, context, definition) { if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') { module.exports = definition(); } else if (typeof define === 'function' && typeof define.amd === 'object') { define(function () { return definition(); }); } else { context[name] = definition(); } }('chai', this, function () { function require(p) { var path = require.resolve(p) , mod = require.modules[path]; if (!mod) throw new Error('failed to require "' + p + '"'); if (!mod.exports) { mod.exports = {}; mod.call(mod.exports, mod, mod.exports, require.relative(path)); } return mod.exports; } require.modules = {}; require.resolve = function (path) { var orig = path , reg = path + '.js' , index = path + '/index.js'; return require.modules[reg] && reg || require.modules[index] && index || orig; }; require.register = function (path, fn) { require.modules[path] = fn; }; require.relative = function (parent) { return function(p){ if ('.' != p.charAt(0)) return require(p); var path = parent.split('/') , segs = p.split('/'); path.pop(); for (var i = 0; i < segs.length; i++) { var seg = segs[i]; if ('..' == seg) path.pop(); else if ('.' != seg) path.push(seg); } return require(path.join('/')); }; }; require.alias = function (from, to) { var fn = require.modules[from]; require.modules[to] = fn; }; require.register("chai.js", function(module, exports, require){ /*! * chai * Copyright(c) 2011-2013 Jake Luer <jake@alogicalparadox.com> * MIT Licensed */ var used = [] , exports = module.exports = {}; /*! * Chai version */ exports.version = '1.5.0'; /*! * Primary `Assertion` prototype */ exports.Assertion = require('./chai/assertion'); /*! * Assertion Error */ exports.AssertionError = require('./chai/error'); /*! * Utils for plugins (not exported) */ var util = require('./chai/utils'); /** * # .use(function) * * Provides a way to extend the internals of Chai * * @param {Function} * @returns {this} for chaining * @api public */ exports.use = function (fn) { if (!~used.indexOf(fn)) { fn(this, util); used.push(fn); } return this; }; /*! * Core Assertions */ var core = require('./chai/core/assertions'); exports.use(core); /*! * Expect interface */ var expect = require('./chai/interface/expect'); exports.use(expect); /*! * Should interface */ var should = require('./chai/interface/should'); exports.use(should); /*! * Assert interface */ var assert = require('./chai/interface/assert'); exports.use(assert); }); // module: chai.js require.register("chai/assertion.js", function(module, exports, require){ /*! * chai * http://chaijs.com * Copyright(c) 2011-2013 Jake Luer <jake@alogicalparadox.com> * MIT Licensed */ /*! * Module dependencies. */ var AssertionError = require('./error') , util = require('./utils') , flag = util.flag; /*! * Module export. */ module.exports = Assertion; /*! * Assertion Constructor * * Creates object for chaining. * * @api private */ function Assertion (obj, msg, stack) { flag(this, 'ssfi', stack || arguments.callee); flag(this, 'object', obj); flag(this, 'message', msg); } /*! * ### Assertion.includeStack * * User configurable property, influences whether stack trace * is included in Assertion error message. Default of false * suppresses stack trace in the error message * * Assertion.includeStack = true; // enable stack on error * * @api public */ Assertion.includeStack = false; /*! * ### Assertion.showDiff * * User configurable property, influences whether or not * the `showDiff` flag should be included in the thrown * AssertionErrors. `false` will always be `false`; `true` * will be true when the assertion has requested a diff * be shown. * * @api public */ Assertion.showDiff = true; Assertion.addProperty = function (name, fn) { util.addProperty(this.prototype, name, fn); }; Assertion.addMethod = function (name, fn) { util.addMethod(this.prototype, name, fn); }; Assertion.addChainableMethod = function (name, fn, chainingBehavior) { util.addChainableMethod(this.prototype, name, fn, chainingBehavior); }; Assertion.overwriteProperty = function (name, fn) { util.overwriteProperty(this.prototype, name, fn); }; Assertion.overwriteMethod = function (name, fn) { util.overwriteMethod(this.prototype, name, fn); }; /*! * ### .assert(expression, message, negateMessage, expected, actual) * * Executes an expression and check expectations. Throws AssertionError for reporting if test doesn't pass. * * @name assert * @param {Philosophical} expression to be tested * @param {String} message to display if fails * @param {String} negatedMessage to display if negated expression fails * @param {Mixed} expected value (remember to check for negation) * @param {Mixed} actual (optional) will default to `this.obj` * @api private */ Assertion.prototype.assert = function (expr, msg, negateMsg, expected, _actual, showDiff) { var ok = util.test(this, arguments); if (true !== showDiff) showDiff = false; if (true !== Assertion.showDiff) showDiff = false; if (!ok) { var msg = util.getMessage(this, arguments) , actual = util.getActual(this, arguments); throw new AssertionError({ message: msg , actual: actual , expected: expected , stackStartFunction: (Assertion.includeStack) ? this.assert : flag(this, 'ssfi') , showDiff: showDiff }); } }; /*! * ### ._obj * * Quick reference to stored `actual` value for plugin developers. * * @api private */ Object.defineProperty(Assertion.prototype, '_obj', { get: function () { return flag(this, 'object'); } , set: function (val) { flag(this, 'object', val); } }); }); // module: chai/assertion.js require.register("chai/core/assertions.js", function(module, exports, require){ /*! * chai * http://chaijs.com * Copyright(c) 2011-2013 Jake Luer <jake@alogicalparadox.com> * MIT Licensed */ module.exports = function (chai, _) { var Assertion = chai.Assertion , toString = Object.prototype.toString , flag = _.flag; /** * ### Language Chains * * The following are provide as chainable getters to * improve the readability of your assertions. They * do not provide an testing capability unless they * have been overwritten by a plugin. * * **Chains** * * - to * - be * - been * - is * - that * - and * - have * - with * - at * - of * * @name language chains * @api public */ [ 'to', 'be', 'been' , 'is', 'and', 'have' , 'with', 'that', 'at' , 'of' ].forEach(function (chain) { Assertion.addProperty(chain, function () { return this; }); }); /** * ### .not * * Negates any of assertions following in the chain. * * expect(foo).to.not.equal('bar'); * expect(goodFn).to.not.throw(Error); * expect({ foo: 'baz' }).to.have.property('foo') * .and.not.equal('bar'); * * @name not * @api public */ Assertion.addProperty('not', function () { flag(this, 'negate', true); }); /** * ### .deep * * Sets the `deep` flag, later used by the `equal` and * `property` assertions. * * expect(foo).to.deep.equal({ bar: 'baz' }); * expect({ foo: { bar: { baz: 'quux' } } }) * .to.have.deep.property('foo.bar.baz', 'quux'); * * @name deep * @api public */ Assertion.addProperty('deep', function () { flag(this, 'deep', true); }); /** * ### .a(type) * * The `a` and `an` assertions are aliases that can be * used either as language chains or to assert a value's * type. * * // typeof * expect('test').to.be.a('string'); * expect({ foo: 'bar' }).to.be.an('object'); * expect(null).to.be.a('null'); * expect(undefined).to.be.an('undefined'); * * // language chain * expect(foo).to.be.an.instanceof(Foo); * * @name a * @alias an * @param {String} type * @param {String} message _optional_ * @api public */ function an (type, msg) { if (msg) flag(this, 'message', msg); type = type.toLowerCase(); var obj = flag(this, 'object') , article = ~[ 'a', 'e', 'i', 'o', 'u' ].indexOf(type.charAt(0)) ? 'an ' : 'a '; this.assert( type === _.type(obj) , 'expected #{this} to be ' + article + type , 'expected #{this} not to be ' + article + type ); } Assertion.addChainableMethod('an', an); Assertion.addChainableMethod('a', an); /** * ### .include(value) * * The `include` and `contain` assertions can be used as either property * based language chains or as methods to assert the inclusion of an object * in an array or a substring in a string. When used as language chains, * they toggle the `contain` flag for the `keys` assertion. * * expect([1,2,3]).to.include(2); * expect('foobar').to.contain('foo'); * expect({ foo: 'bar', hello: 'universe' }).to.include.keys('foo'); * * @name include * @alias contain * @param {Object|String|Number} obj * @param {String} message _optional_ * @api public */ function includeChainingBehavior () { flag(this, 'contains', true); } function include (val, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object') this.assert( ~obj.indexOf(val) , 'expected #{this} to include ' + _.inspect(val) , 'expected #{this} to not include ' + _.inspect(val)); } Assertion.addChainableMethod('include', include, includeChainingBehavior); Assertion.addChainableMethod('contain', include, includeChainingBehavior); /** * ### .ok * * Asserts that the target is truthy. * * expect('everthing').to.be.ok; * expect(1).to.be.ok; * expect(false).to.not.be.ok; * expect(undefined).to.not.be.ok; * expect(null).to.not.be.ok; * * @name ok * @api public */ Assertion.addProperty('ok', function () { this.assert( flag(this, 'object') , 'expected #{this} to be truthy' , 'expected #{this} to be falsy'); }); /** * ### .true * * Asserts that the target is `true`. * * expect(true).to.be.true; * expect(1).to.not.be.true; * * @name true * @api public */ Assertion.addProperty('true', function () { this.assert( true === flag(this, 'object') , 'expected #{this} to be true' , 'expected #{this} to be false' , this.negate ? false : true ); }); /** * ### .false * * Asserts that the target is `false`. * * expect(false).to.be.false; * expect(0).to.not.be.false; * * @name false * @api public */ Assertion.addProperty('false', function () { this.assert( false === flag(this, 'object') , 'expected #{this} to be false' , 'expected #{this} to be true' , this.negate ? true : false ); }); /** * ### .null * * Asserts that the target is `null`. * * expect(null).to.be.null; * expect(undefined).not.to.be.null; * * @name null * @api public */ Assertion.addProperty('null', function () { this.assert( null === flag(this, 'object') , 'expected #{this} to be null' , 'expected #{this} not to be null' ); }); /** * ### .undefined * * Asserts that the target is `undefined`. * * expect(undefined).to.be.undefined; * expect(null).to.not.be.undefined; * * @name undefined * @api public */ Assertion.addProperty('undefined', function () { this.assert( undefined === flag(this, 'object') , 'expected #{this} to be undefined' , 'expected #{this} not to be undefined' ); }); /** * ### .exist * * Asserts that the target is neither `null` nor `undefined`. * * var foo = 'hi' * , bar = null * , baz; * * expect(foo).to.exist; * expect(bar).to.not.exist; * expect(baz).to.not.exist; * * @name exist * @api public */ Assertion.addProperty('exist', function () { this.assert( null != flag(this, 'object') , 'expected #{this} to exist' , 'expected #{this} to not exist' ); }); /** * ### .empty * * Asserts that the target's length is `0`. For arrays, it checks * the `length` property. For objects, it gets the count of * enumerable keys. * * expect([]).to.be.empty; * expect('').to.be.empty; * expect({}).to.be.empty; * * @name empty * @api public */ Assertion.addProperty('empty', function () { var obj = flag(this, 'object') , expected = obj; if (Array.isArray(obj) || 'string' === typeof object) { expected = obj.length; } else if (typeof obj === 'object') { expected = Object.keys(obj).length; } this.assert( !expected , 'expected #{this} to be empty' , 'expected #{this} not to be empty' ); }); /** * ### .arguments * * Asserts that the target is an arguments object. * * function test () { * expect(arguments).to.be.arguments; * } * * @name arguments * @alias Arguments * @api public */ function checkArguments () { var obj = flag(this, 'object') , type = Object.prototype.toString.call(obj); this.assert( '[object Arguments]' === type , 'expected #{this} to be arguments but got ' + type , 'expected #{this} to not be arguments' ); } Assertion.addProperty('arguments', checkArguments); Assertion.addProperty('Arguments', checkArguments); /** * ### .equal(value) * * Asserts that the target is strictly equal (`===`) to `value`. * Alternately, if the `deep` flag is set, asserts that * the target is deeply equal to `value`. * * expect('hello').to.equal('hello'); * expect(42).to.equal(42); * expect(1).to.not.equal(true); * expect({ foo: 'bar' }).to.not.equal({ foo: 'bar' }); * expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' }); * * @name equal * @alias equals * @alias eq * @alias deep.equal * @param {Mixed} value * @param {String} message _optional_ * @api public */ function assertEqual (val, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); if (flag(this, 'deep')) { return this.eql(val); } else { this.assert( val === obj , 'expected #{this} to equal #{exp}' , 'expected #{this} to not equal #{exp}' , val , this._obj , true ); } } Assertion.addMethod('equal', assertEqual); Assertion.addMethod('equals', assertEqual); Assertion.addMethod('eq', assertEqual); /** * ### .eql(value) * * Asserts that the target is deeply equal to `value`. * * expect({ foo: 'bar' }).to.eql({ foo: 'bar' }); * expect([ 1, 2, 3 ]).to.eql([ 1, 2, 3 ]); * * @name eql * @alias eqls * @param {Mixed} value * @param {String} message _optional_ * @api public */ function assertEql(obj, msg) { if (msg) flag(this, 'message', msg); this.assert( _.eql(obj, flag(this, 'object')) , 'expected #{this} to deeply equal #{exp}' , 'expected #{this} to not deeply equal #{exp}' , obj , this._obj , true ); } Assertion.addMethod('eql', assertEql); Assertion.addMethod('eqls', assertEql); /** * ### .above(value) * * Asserts that the target is greater than `value`. * * expect(10).to.be.above(5); * * Can also be used in conjunction with `length` to * assert a minimum length. The benefit being a * more informative error message than if the length * was supplied directly. * * expect('foo').to.have.length.above(2); * expect([ 1, 2, 3 ]).to.have.length.above(2); * * @name above * @alias gt * @alias greaterThan * @param {Number} value * @param {String} message _optional_ * @api public */ function assertAbove (n, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); if (flag(this, 'doLength')) { new Assertion(obj, msg).to.have.property('length'); var len = obj.length; this.assert( len > n , 'expected #{this} to have a length above #{exp} but got #{act}' , 'expected #{this} to not have a length above #{exp}' , n , len ); } else { this.assert( obj > n , 'expected #{this} to be above ' + n , 'expected #{this} to be at most ' + n ); } } Assertion.addMethod('above', assertAbove); Assertion.addMethod('gt', assertAbove); Assertion.addMethod('greaterThan', assertAbove); /** * ### .least(value) * * Asserts that the target is greater than or equal to `value`. * * expect(10).to.be.at.least(10); * * Can also be used in conjunction with `length` to * assert a minimum length. The benefit being a * more informative error message than if the length * was supplied directly. * * expect('foo').to.have.length.of.at.least(2); * expect([ 1, 2, 3 ]).to.have.length.of.at.least(3); * * @name least * @alias gte * @param {Number} value * @param {String} message _optional_ * @api public */ function assertLeast (n, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); if (flag(this, 'doLength')) { new Assertion(obj, msg).to.have.property('length'); var len = obj.length; this.assert( len >= n , 'expected #{this} to have a length at least #{exp} but got #{act}' , 'expected #{this} to have a length below #{exp}' , n , len ); } else { this.assert( obj >= n , 'expected #{this} to be at least ' + n , 'expected #{this} to be below ' + n ); } } Assertion.addMethod('least', assertLeast); Assertion.addMethod('gte', assertLeast); /** * ### .below(value) * * Asserts that the target is less than `value`. * * expect(5).to.be.below(10); * * Can also be used in conjunction with `length` to * assert a maximum length. The benefit being a * more informative error message than if the length * was supplied directly. * * expect('foo').to.have.length.below(4); * expect([ 1, 2, 3 ]).to.have.length.below(4); * * @name below * @alias lt * @alias lessThan * @param {Number} value * @param {String} message _optional_ * @api public */ function assertBelow (n, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); if (flag(this, 'doLength')) { new Assertion(obj, msg).to.have.property('length'); var len = obj.length; this.assert( len < n , 'expected #{this} to have a length below #{exp} but got #{act}' , 'expected #{this} to not have a length below #{exp}' , n , len ); } else { this.assert( obj < n , 'expected #{this} to be below ' + n , 'expected #{this} to be at least ' + n ); } } Assertion.addMethod('below', assertBelow); Assertion.addMethod('lt', assertBelow); Assertion.addMethod('lessThan', assertBelow); /** * ### .most(value) * * Asserts that the target is less than or equal to `value`. * * expect(5).to.be.at.most(5); * * Can also be used in conjunction with `length` to * assert a maximum length. The benefit being a * more informative error message than if the length * was supplied directly. * * expect('foo').to.have.length.of.at.most(4); * expect([ 1, 2, 3 ]).to.have.length.of.at.most(3); * * @name most * @alias lte * @param {Number} value * @param {String} message _optional_ * @api public */ function assertMost (n, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); if (flag(this, 'doLength')) { new Assertion(obj, msg).to.have.property('length'); var len = obj.length; this.assert( len <= n , 'expected #{this} to have a length at most #{exp} but got #{act}' , 'expected #{this} to have a length above #{exp}' , n , len ); } else { this.assert( obj <= n , 'expected #{this} to be at most ' + n , 'expected #{this} to be above ' + n ); } } Assertion.addMethod('most', assertMost); Assertion.addMethod('lte', assertMost); /** * ### .within(start, finish) * * Asserts that the target is within a range. * * expect(7).to.be.within(5,10); * * Can also be used in conjunction with `length` to * assert a length range. The benefit being a * more informative error message than if the length * was supplied directly. * * expect('foo').to.have.length.within(2,4); * expect([ 1, 2, 3 ]).to.have.length.within(2,4); * * @name within * @param {Number} start lowerbound inclusive * @param {Number} finish upperbound inclusive * @param {String} message _optional_ * @api public */ Assertion.addMethod('within', function (start, finish, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object') , range = start + '..' + finish; if (flag(this, 'doLength')) { new Assertion(obj, msg).to.have.property('length'); var len = obj.length; this.assert( len >= start && len <= finish , 'expected #{this} to have a length within ' + range , 'expected #{this} to not have a length within ' + range ); } else { this.assert( obj >= start && obj <= finish , 'expected #{this} to be within ' + range , 'expected #{this} to not be within ' + range ); } }); /** * ### .instanceof(constructor) * * Asserts that the target is an instance of `constructor`. * * var Tea = function (name) { this.name = name; } * , Chai = new Tea('chai'); * * expect(Chai).to.be.an.instanceof(Tea); * expect([ 1, 2, 3 ]).to.be.instanceof(Array); * * @name instanceof * @param {Constructor} constructor * @param {String} message _optional_ * @alias instanceOf * @api public */ function assertInstanceOf (constructor, msg) { if (msg) flag(this, 'message', msg); var name = _.getName(constructor); this.assert( flag(this, 'object') instanceof constructor , 'expected #{this} to be an instance of ' + name , 'expected #{this} to not be an instance of ' + name ); }; Assertion.addMethod('instanceof', assertInstanceOf); Assertion.addMethod('instanceOf', assertInstanceOf); /** * ### .property(name, [value]) * * Asserts that the target has a property `name`, optionally asserting that * the value of that property is strictly equal to `value`. * If the `deep` flag is set, you can use dot- and bracket-notation for deep * references into objects and arrays. * * // simple referencing * var obj = { foo: 'bar' }; * expect(obj).to.have.property('foo'); * expect(obj).to.have.property('foo', 'bar'); * * // deep referencing * var deepObj = { * green: { tea: 'matcha' } * , teas: [ 'chai', 'matcha', { tea: 'konacha' } ] * }; * expect(deepObj).to.have.deep.property('green.tea', 'matcha'); * expect(deepObj).to.have.deep.property('teas[1]', 'matcha'); * expect(deepObj).to.have.deep.property('teas[2].tea', 'konacha'); * * You can also use an array as the starting point of a `deep.property` * assertion, or traverse nested arrays. * * var arr = [ * [ 'chai', 'matcha', 'konacha' ] * , [ { tea: 'chai' } * , { tea: 'matcha' } * , { tea: 'konacha' } ] * ]; * * expect(arr).to.have.deep.property('[0][1]', 'matcha'); * expect(arr).to.have.deep.property('[1][2].tea', 'konacha'); * * Furthermore, `property` changes the subject of the assertion * to be the value of that property from the original object. This * permits for further chainable assertions on that property. * * expect(obj).to.have.property('foo') * .that.is.a('string'); * expect(deepObj).to.have.property('green') * .that.is.an('object') * .that.deep.equals({ tea: 'matcha' }); * expect(deepObj).to.have.property('teas') * .that.is.an('array') * .with.deep.property('[2]') * .that.deep.equals({ tea: 'konacha' }); * * @name property * @alias deep.property * @param {String} name * @param {Mixed} value (optional) * @param {String} message _optional_ * @returns value of property for chaining * @api public */ Assertion.addMethod('property', function (name, val, msg) { if (msg) flag(this, 'message', msg); var descriptor = flag(this, 'deep') ? 'deep property ' : 'property ' , negate = flag(this, 'negate') , obj = flag(this, 'object') , value = flag(this, 'deep') ? _.getPathValue(name, obj) : obj[name]; if (negate && undefined !== val) { if (undefined === value) { msg = (msg != null) ? msg + ': ' : ''; throw new Error(msg + _.inspect(obj) + ' has no ' + descriptor + _.inspect(name)); } } else { this.assert( undefined !== value , 'expected #{this} to have a ' + descriptor + _.inspect(name) , 'expected #{this} to not have ' + descriptor + _.inspect(name)); } if (undefined !== val) { this.assert( val === value , 'expected #{this} to have a ' + descriptor + _.inspect(name) + ' of #{exp}, but got #{act}' , 'expected #{this} to not have a ' + descriptor + _.inspect(name) + ' of #{act}' , val , value ); } flag(this, 'object', value); }); /** * ### .ownProperty(name) * * Asserts that the target has an own property `name`. * * expect('test').to.have.ownProperty('length'); * * @name ownProperty * @alias haveOwnProperty * @param {String} name * @param {String} message _optional_ * @api public */ function assertOwnProperty (name, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); this.assert( obj.hasOwnProperty(name) , 'expected #{this} to have own property ' + _.inspect(name) , 'expected #{this} to not have own property ' + _.inspect(name) ); } Assertion.addMethod('ownProperty', assertOwnProperty); Assertion.addMethod('haveOwnProperty', assertOwnProperty); /** * ### .length(value) * * Asserts that the target's `length` property has * the expected value. * * expect([ 1, 2, 3]).to.have.length(3); * expect('foobar').to.have.length(6); * * Can also be used as a chain precursor to a value * comparison for the length property. * * expect('foo').to.have.length.above(2); * expect([ 1, 2, 3 ]).to.have.length.above(2); * expect('foo').to.have.length.below(4); * expect([ 1, 2, 3 ]).to.have.length.below(4); * expect('foo').to.have.length.within(2,4); * expect([ 1, 2, 3 ]).to.have.length.within(2,4); * * @name length * @alias lengthOf * @param {Number} length * @param {String} message _optional_ * @api public */ function assertLengthChain () { flag(this, 'doLength', true); } function assertLength (n, msg) { if (msg) flag(this, 'message', msg); var obj = flag(this, 'object'); new Assertion(obj, msg).to.have.property('length'); var len = obj.length; this.assert( len == n , 'expected #{this} to have a length of #{exp} but got #{act}' , 'expected #{this} to not have a length of #{act}' , n , len ); } Assertion.addChainableMethod('length', assertLength, assertLengthChain); Assertion.addMethod('lengthOf', assertLength, assertLengthChain); /** * ### .match(regexp) * * Asserts that the target matches a regular expression. * * expect('foobar').to.match(/^foo/); * * @name match * @param {RegExp} RegularExpression * @param {String} message _optional_ * @api public */ Assertion.addMethod('match', function (re, msg) {
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
true
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/common/test/common-logic-test.js
src/common/test/common-logic-test.js
/* * Copyright Adam Pritchard 2013 * MIT License : https://adampritchard.mit-license.org/ */ "use strict"; /* jshint curly:true, noempty:true, newcap:true, eqeqeq:true, eqnull:true, undef:true, devel:true, browser:true, node:true, evil:false, latedef:false, nonew:true, trailing:false, immed:false, smarttabs:true, expr:true */ /* global describe, expect, it, before, beforeEach, after, afterEach */ /* global _, $, markdownRender, htmlToText, marked, hljs, Utils, CommonLogic */ describe('CommonLogic', function() { it('should exist', function() { expect(CommonLogic).to.exist; }); describe('getForgotToRenderPromptContent', function() { it('should get the forgot-to-render prompt', function(done) { var KNOWN_CONTENT = 'id="markdown-here-forgot-to-render"'; var callback = function(data) { expect(data.indexOf(KNOWN_CONTENT)).to.be.greaterThan(-1); done(); }; CommonLogic.getForgotToRenderPromptContent(callback); }); }); describe('probablyWritingMarkdown', function() { var prefs = {}; it('should not detect an empty string', function() { expect(CommonLogic.probablyWritingMarkdown('', marked, prefs)).to.equal(false); }); it('should not detect non-MD text', function() { var text = 'Hi friend,\n\nHow are you?\n\nsincerely,\nme'; expect(CommonLogic.probablyWritingMarkdown(text, marked, prefs)).to.equal(false); }); it('should detect bullets', function() { var text = 'Hi friend,\n\nHow are you?\n\n* bullet 1\n * sub-bullet\n* bullet 2\n\nsincerely,\nme'; expect(CommonLogic.probablyWritingMarkdown(text, marked, prefs)).to.equal(true); }); it('should detect code', function() { var text = 'Hi friend,\n\nHow are you?\n\nHere is `code`.\n\nsincerely,\nme'; expect(CommonLogic.probablyWritingMarkdown(text, marked, prefs)).to.equal(true); text = 'Hi friend,\n\nHow are you?\n\n```javascript\nvar s = "code";\n```\n\nsincerely,\nme'; expect(CommonLogic.probablyWritingMarkdown(text, marked, prefs)).to.equal(true); }); it('should detect math', function() { var text = 'Hi friend,\n\nHow are you?\n\n$\\delta$\n\nsincerely,\nme'; expect(CommonLogic.probablyWritingMarkdown(text, marked, prefs)).to.equal(true); }); it('should detect emphasis', function() { var text = 'Hi friend,\n\nHow are you?\n\nSo **strong**!\n\nsincerely,\nme'; expect(CommonLogic.probablyWritingMarkdown(text, marked, prefs)).to.equal(true); // But not light emphasis. text = 'Hi friend,\n\nHow are you?\n\nSo _weak_!\n\nsincerely,\nme'; expect(CommonLogic.probablyWritingMarkdown(text, marked, prefs)).to.equal(false); }); it('should detect headers', function() { var text = 'Hi friend,\n\nHow are you?\n\n## IMAHEADER\n\nsincerely,\nme'; expect(CommonLogic.probablyWritingMarkdown(text, marked, prefs)).to.equal(true); text = 'Hi friend,\n\nHow are you?\n\n###### IMAHEADER\n\nsincerely,\nme'; expect(CommonLogic.probablyWritingMarkdown(text, marked, prefs)).to.equal(true); text = 'Hi friend,\n\nHow are you?\n\n ## SPACES BEFORE HASHES AND AFTER TEXT \n\nsincerely,\nme'; expect(CommonLogic.probablyWritingMarkdown(text, marked, prefs)).to.equal(true); text = 'Hi friend,\n\nHow are you?\n\n####### TOO MANY HASH MARKS\n\nsincerely,\nme'; expect(CommonLogic.probablyWritingMarkdown(text, marked, prefs)).to.equal(false); text = 'Hi friend,\n\nHow are you?\n\nUNDERLINE HEADER\n------\n\nsincerely,\nme'; expect(CommonLogic.probablyWritingMarkdown(text, marked, prefs)).to.equal(true); text = 'Hi friend,\n\nHow are you?\n\nUNDERLINE HEADER\n======\n\nsincerely,\nme'; expect(CommonLogic.probablyWritingMarkdown(text, marked, prefs)).to.equal(true); text = 'Hi friend,\n\nHow are you?\n\nSPACES BEFORE DASHES OKAY\n ======\n\nsincerely,\nme'; expect(CommonLogic.probablyWritingMarkdown(text, marked, prefs)).to.equal(true); text = 'Hi friend,\n\nHow are you?\n\n===== TEXT AFTER UNDERLINE\n\nsincerely,\nme'; expect(CommonLogic.probablyWritingMarkdown(text, marked, prefs)).to.equal(false); }); it('should detect links', function() { var text = 'Hi friend,\n\nHow are you?\n\n[The Goog](https://www.google.com)\n\nsincerely,\nme'; expect(CommonLogic.probablyWritingMarkdown(text, marked, prefs)).to.equal(true); text = 'Hi friend,\n\nHow are you?\n\n[The Goog][1]\n\nsincerely,\nme\n\n[1]: https://www.google.com'; expect(CommonLogic.probablyWritingMarkdown(text, marked, prefs)).to.equal(true); text = 'Hi friend,\n\nHow are you?\n\n[Not a nolink link].\n\nsincerely,\nme\n\n'; expect(CommonLogic.probablyWritingMarkdown(text, marked, prefs)).to.equal(false); }); }); });
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
false
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/common/test/utils-test.js
src/common/test/utils-test.js
/* * Copyright Adam Pritchard 2014 * MIT License : https://adampritchard.mit-license.org/ */ "use strict"; /* jshint curly:true, noempty:true, newcap:true, eqeqeq:true, eqnull:true, es5:true, undef:true, devel:true, browser:true, node:true, evil:false, latedef:false, nonew:true, trailing:false, immed:false, smarttabs:true, expr:true */ /* global describe, expect, it, before, beforeEach, after, afterEach */ /* global _, markdownRender, htmlToText, marked, hljs, Utils */ // This function wraps `htmlString` in a `<div>` to make life easier for us. // It should affect the testing behaviour, though -- good/bad elements in a // `<div>` are still good/bad. function createDocFrag(htmlString) { const docFrag = document.createDocumentFragment(); const elem = document.createElement('div'); elem.innerHTML = htmlString; docFrag.appendChild(elem); return docFrag; } describe('Utils', function() { it('should exist', function() { expect(Utils).to.exist; }); describe('saferSetInnerHTML', function() { it('should set safe HTML without alteration', function() { var testElem = document.createElement('div'); Utils.saferSetInnerHTML(testElem, '<p>hi</p>'); var checkElem = document.createElement('div'); checkElem.innerHTML = '<p>hi</p>'; expect(testElem.isEqualNode(checkElem)).to.be.true; }); it('should remove <script> elements', function() { var testElem = document.createElement('div'); Utils.saferSetInnerHTML(testElem, '<b>hi</b><script>alert("oops")</script>there<script>alert("derp")</script>'); var checkElem = document.createElement('div'); checkElem.innerHTML = '<b>hi</b><script>alert("oops")</script>there<script>alert("derp")</script>'; expect(testElem.isEqualNode(checkElem)).to.be.false; var safeElem = document.createElement('div'); safeElem.innerHTML = '<b>hi</b>there'; expect(testElem.isEqualNode(safeElem)).to.be.true; }); it('should not remove safe attributes', function() { var testElem = document.createElement('div'); Utils.saferSetInnerHTML(testElem, '<div id="rad" style="color:red">hi</div>'); var checkElem = document.createElement('div'); checkElem.innerHTML = '<div id="rad" style="color:red">hi</div>'; expect(testElem.isEqualNode(checkElem)).to.be.true; expect(testElem.querySelector('#rad').style.color).to.equal('red'); }); it('should remove event handler attributes', function() { var testElem = document.createElement('div'); Utils.saferSetInnerHTML(testElem, '<div id="rad" style="color:red" onclick="javascript:alert(\'derp\')">hi</div>'); var checkElem = document.createElement('div'); checkElem.innerHTML = '<div id="rad" style="color:red">hi</div>'; expect(testElem.isEqualNode(checkElem)).to.be.true; expect(testElem.querySelector('#rad').style.color).to.equal('red'); expect(testElem.querySelector('#rad').attributes.onclick).to.not.exist; }); }); describe('saferSetOuterHTML', function() { beforeEach(function() { // Our test container element, which will not be modified const container = document.createElement('div'); container.id = 'test-container'; container.style.display = 'none'; container.innerHTML = '<div id="test-elem"></div>'; document.body.appendChild(container); }); afterEach(function() { const container = document.getElementById('test-container'); if (container && container.parentNode) { container.parentNode.removeChild(container); } }); it('should throw exception if element not in DOM', function() { const testElem = document.createElement('div'); testElem.innerHTML = '<b>bye</b>'; const fn = _.partial(Utils.saferSetOuterHTML, '<p></p>'); expect(fn).to.throw(Error); }); it('should set safe HTML without alteration', function() { const container = document.getElementById('test-container'); Utils.saferSetOuterHTML(container.firstElementChild, '<p>hi</p>'); expect(container.innerHTML).to.equal('<p>hi</p>'); }); it('should remove <script> elements', function() { const container = document.getElementById('test-container'); Utils.saferSetOuterHTML(container.firstElementChild, '<b>hi</b><script>alert("oops")</script>there<script>alert("derp")</script>'); expect(container.innerHTML).to.equal('<b>hi</b>there'); }); it('should not remove safe attributes', function() { const container = document.getElementById('test-container'); Utils.saferSetOuterHTML(container.firstElementChild, '<div id="rad" style="color:red">hi</div>'); expect(container.innerHTML).to.equal('<div id="rad" style="color:red">hi</div>'); }); it('should remove event handler attributes', function() { const container = document.getElementById('test-container'); Utils.saferSetOuterHTML(container.firstElementChild, '<div id="rad" style="color:red" onclick="javascript:alert(\'derp\')">hi</div>'); expect(container.innerHTML).to.equal('<div id="rad" style="color:red">hi</div>'); }); // An earlier implementation of Utils.saferSetOuterHTML was vulnerable to allowing // script execution through the on error and onload handlers of an image element. // Unfortunately, on the test page this manifested as a CSP error, so this test never // actually failed, even when the vulnerability was present. This test is a reminder // of that vulnerability, and there should not be any console CSP errors when it is run. it('should not execute img onerror handlers', function() { // Another test showing script execution through different vectors window.imgErrorExecuted = false; var maliciousHTML = '<div>before</div><img src="nonexistent.jpg" onerror="window.imgErrorExecuted = true;"><div>after</div>'; const container = document.getElementById('test-container'); Utils.saferSetOuterHTML(container.firstElementChild, maliciousHTML); // The onerror handler should NOT have executed expect(window.imgErrorExecuted).to.be.false; // Clean up delete window.imgErrorExecuted; }); }); describe('getDocumentFragmentHTML', function() { const makeFragment = function(htmlArray) { const docFrag = document.createDocumentFragment(); htmlArray.forEach(function(html) { const template = document.createElement('template'); template.innerHTML = html; docFrag.appendChild(template.content.firstElementChild); }); return docFrag; }; const makeTextFragment = function(text) { const docFrag = document.createDocumentFragment(); const textNode = document.createTextNode(text); docFrag.appendChild(textNode); return docFrag; }; it('should be okay with an empty fragment', function() { expect(Utils.getDocumentFragmentHTML(makeFragment([]))).to.equal(''); }); it('should return correct html', function() { var htmlArray = [ '<div>aaa</div>', '<span><b>bbb</b></span>' ]; var expectedHTML = htmlArray.join(''); expect(Utils.getDocumentFragmentHTML(makeFragment(htmlArray))).to.equal(expectedHTML); }); // Test issue #133: https://github.com/adam-p/markdown-here/issues/133 // Thunderbird: raw HTML not rendering properly. // HTML text nodes were not being escaped properly. it('should escape HTML in a text node', function() { var docFrag = makeTextFragment('<span style="color:blue">im&blue</span>'); var expectedHTML = '&lt;span style="color:blue"&gt;im&amp;blue&lt;/span&gt;'; expect(Utils.getDocumentFragmentHTML(docFrag)).to.equal(expectedHTML); }); }); describe('isElementDescendant', function() { let testOuter; before(function() { testOuter = document.createElement('div'); testOuter.id = 'isElementDescendant-0'; testOuter.innerHTML = '<div id="isElementDescendant-1"><div id="isElementDescendant-1-1"></div></div>' + '<div id="isElementDescendant-2"><div id="isElementDescendant-2-1"></div></div>'; document.body.appendChild(testOuter); }); after(function() { if (testOuter && testOuter.parentNode) { testOuter.parentNode.removeChild(testOuter); } }); it('should correctly detect descendency', function() { expect(Utils.isElementDescendant( document.querySelector('#isElementDescendant-2'), document.querySelector('#isElementDescendant-2-1'))).to.equal(true); expect(Utils.isElementDescendant( document.querySelector('#isElementDescendant-0'), document.querySelector('#isElementDescendant-2-1'))).to.equal(true); }); it('should correctly detect non-descendency', function() { expect(Utils.isElementDescendant( document.querySelector('#isElementDescendant-2-1'), document.querySelector('#isElementDescendant-2'))).to.equal(false); expect(Utils.isElementDescendant( document.querySelector('#isElementDescendant-2-1'), document.querySelector('#isElementDescendant-0'))).to.equal(false); expect(Utils.isElementDescendant( document.querySelector('#isElementDescendant-1'), document.querySelector('#isElementDescendant-2'))).to.equal(false); }); }); describe('getLocalFile', function() { it('should return correct text data', function(done) { var KNOWN_PREFIX = '<!DOCTYPE html>'; var callback = function(data) { expect(data.slice(0, KNOWN_PREFIX.length)).to.equal(KNOWN_PREFIX); done(); }; Utils.getLocalFile('../options.html', 'text', callback); }); it('should return correct json data', function(done) { var callback = function(data) { expect(data).to.be.an('object'); expect(data).to.have.property('app_name'); done(); }; Utils.getLocalFile('/_locales/en/messages.json', 'json', callback); }); it('should return correct base64 data', function(done) { // We "know" our logo file starts with this string when base64'd var KNOWN_PREFIX = 'iVBORw0KGgo'; var callback = function(data) { expect(data.slice(0, KNOWN_PREFIX.length)).to.equal(KNOWN_PREFIX); done(); }; Utils.getLocalFile('../images/icon16.png', 'base64', callback); }); it('should work with getLocalURL', function(done) { var KNOWN_PREFIX = '<!DOCTYPE html>'; var callback = function(data) { expect(data.slice(0, KNOWN_PREFIX.length)).to.equal(KNOWN_PREFIX); done(); }; Utils.getLocalFile(Utils.getLocalURL('/common/options.html'), 'text', callback); }); /* If we switch to promises rather than asynchronous callbacks, we can use these tests again. it('should supply an error arg to callback if file not found', function(done) { try { Utils.getLocalFile('badfilename', 'text', function(val, err) { }); } catch (e) { done(); } }); it('should supply an error arg to callback if dataType is bad', function(done) { Utils.getLocalFile('../options.html', 'nope', function(val, err) { expect(err).to.be.ok; expect(val).to.not.be.ok; done(); }); }); */ }); describe('getLocalURL', function() { it('should return a URL that can be used successfully', function(done) { // We're going to cheat a little and use the URL in a request to make // sure it works. // It would be tough to test otherwise without replicating the internal // logic of the function. var KNOWN_PREFIX = '<!DOCTYPE html>'; var callback = function(data) { expect(data.slice(0, KNOWN_PREFIX.length)).to.equal(KNOWN_PREFIX); done(); }; var url = Utils.getLocalURL('/common/options.html'); Utils.getLocalFile(url, 'text', callback); }); }); describe('fireMouseClick', function() { it('should properly fire a click event', function(done) { var elem = document.createElement('button'); document.body.appendChild(elem); elem.addEventListener('click', function(event) { expect(event[Utils.MARKDOWN_HERE_EVENT]).to.be.true; document.body.removeChild(elem); done(); }); Utils.fireMouseClick(elem); }); }); describe('makeRequestToPrivilegedScript', function() { it('should communicate with privileged script', function(done) { Utils.makeRequestToPrivilegedScript( document, { action: 'test-request' }, function(response) { expect(response).to.equal('test-request-good'); done(); }); }); }); describe('setFocus', function() { it('should set focus into a contenteditable div', function() { const div = document.createElement('div'); div.contentEditable = 'true'; document.body.appendChild(div); expect(document.activeElement).to.not.equal(div); Utils.setFocus(div); expect(document.activeElement).to.equal(div); div.parentNode.removeChild(div); }); it('should set focus into an iframe with contenteditable body', function() { const iframe = document.createElement('iframe'); document.body.appendChild(iframe); iframe.contentDocument.body.contentEditable = true; expect(document.activeElement).to.not.equal(iframe); Utils.setFocus(iframe.contentDocument.body); expect(document.activeElement).to.equal(iframe); expect(iframe.contentDocument.activeElement).to.equal(iframe.contentDocument.body); iframe.parentNode.removeChild(iframe); }); }); describe('setFocus', function() { it('should not explode', function() { Utils.consoleLog('setFocus did not explode'); }); }); describe('getTopURL', function() { it('should get the URL in a simple case', function() { expect(Utils.getTopURL(window)).to.equal(location.href); }); it('should get the URL from an iframe', function() { const iframe = document.createElement('iframe'); document.body.appendChild(iframe); expect(Utils.getTopURL(iframe.contentWindow)).to.equal(location.href); iframe.parentNode.removeChild(iframe); }); it('should get the hostname', function() { expect(Utils.getTopURL(window, true)).to.equal(location.hostname); }); }); describe('nextTick', function() { it('should call callback asynchronously and quickly', function(done) { var start = new Date(); var called = false; Utils.nextTick(function() { called = true; expect(new Date() - start).to.be.lessThan(200); done(); }); expect(called).to.equal(false); }); it('should properly set context', function(done) { var ctx = { hi: 'there' }; Utils.nextTick(function() { expect(this).to.equal(ctx); done(); }, ctx); }); }); describe('nextTickFn', function() { it('should return a function', function() { expect(Utils.nextTickFn(function(){})).to.be.a('function'); }); it('should return a function that calls callback asynchronously and quickly', function(done) { var start = new Date(); var called = false; var fn = Utils.nextTickFn(function() { called = true; expect(new Date() - start).to.be.lessThan(200); done(); }); fn(); expect(called).to.equal(false); }); it('should properly set context', function(done) { var ctx = { hi: 'there' }; var fn = Utils.nextTickFn(function() { expect(this).to.equal(ctx); done(); }, ctx); fn(); }); }); describe('getMessage', function() { it('should return a string', function() { // Since the exact string retuned depends on the current browser locale, // we'll just check that some string is returned. expect(Utils.getMessage('options_page__page_title')).to.be.a('string'); }); it('should throw on bad message ID', function() { var fn = _.partial(Utils.getMessage, 'BAADF00D'); expect(fn).to.throw(Error); }); }); describe('semverGreaterThan', function() { it('should correctly order version strings', function() { // Since the exact string retuned depends on the current browser locale, // we'll just check that some string is returned. expect(Utils.semverGreaterThan('1.11.1', '1.2.2')).to.be.true; expect(Utils.semverGreaterThan('11.1.1', '2.2.2')).to.be.true; expect(Utils.semverGreaterThan('11.1.1', '11.1.0')).to.be.true; expect(Utils.semverGreaterThan('9.0.0', '10.0.0')).to.be.false; expect(Utils.semverGreaterThan('9.0.2', '9.0.100')).to.be.false; expect(Utils.semverGreaterThan('0.99', '1.0')).to.be.false; }); it('should cope with non-semver input', function() { expect(Utils.semverGreaterThan('nope', '1.0')).to.be.true.and.to.not.throw; expect(Utils.semverGreaterThan('1.0', 'nope')).to.be.false.and.to.not.throw; }); it('should return false on falsy input', function() { expect(Utils.semverGreaterThan(null, '1.0')).to.be.false; expect(Utils.semverGreaterThan('1.0', null)).to.be.false; }); }); describe('walkDOM', function() { beforeEach(function() { const container = document.createElement('div'); container.id = 'test-container'; container.style.display = 'none'; container.innerHTML = '<div id="test-elem"></div>'; document.body.appendChild(container); }); afterEach(function() { const container = document.getElementById('test-container'); if (container && container.parentNode) { container.parentNode.removeChild(container); } }); it('should find an element in the DOM', function() { let found = false; Utils.walkDOM(document.body, function(node) { found = found || node.id === 'test-elem'; }); expect(found).to.be.true; }); }); describe('utf8StringToBase64', function() { it('should correctly encode a foreign-character string', function() { var str = 'hello, こんにちは'; var base64 = 'aGVsbG8sIOOBk+OCk+OBq+OBoeOBrw=='; expect(Utils.utf8StringToBase64(str)).to.equal(base64); }); }); describe('base64ToUTF8String', function() { it('should correctly encode a foreign-character string', function() { var str = 'این یک جمله آزمون است.'; var base64 = '2KfbjNmGINuM2qkg2KzZhdmE2Ycg2KLYstmF2YjZhiDYp9iz2Kou'; expect(Utils.base64ToUTF8String(base64)).to.equal(str); }); }); describe('rangeIntersectsNode', function() { beforeEach(function() { const container = document.createElement('div'); container.id = 'test-container'; container.style.display = 'none'; container.innerHTML = '<div id="test-elem-1"></div><div id="test-elem-2"></div>'; document.body.appendChild(container); }); afterEach(function() { const container = document.getElementById('test-container'); if (container && container.parentNode) { container.parentNode.removeChild(container); } }); it('should detect a node in a range', function() { const range = document.createRange(); const container = document.getElementById('test-container'); range.selectNode(container); // Check the node that is selected. expect(Utils.rangeIntersectsNode(range, container)).to.be.true; // Check a node that is within the node that is selected. expect(Utils.rangeIntersectsNode(range, document.getElementById('test-elem-2'))).to.be.true; }); it('should not detect a node not in a range', function() { const range = document.createRange(); range.selectNode(document.getElementById('test-elem-1')); // The parent of the selected node *is* intersected. expect(Utils.rangeIntersectsNode(range, document.getElementById('test-container'))).to.be.true; // The sibling of the selected node *is not* intersected. expect(Utils.rangeIntersectsNode(range, document.getElementById('test-elem-2'))).to.be.false; }); // I have found that Range.intersectsNode is broken on Chrome. I'm adding // test to see if/when it gets fixed. // TODO: This test seems flawed. Why would test-elem-2 intersect the range that just contains test-elem-1? Hand-testing suggests that this is working as expected in Chrome and Firefox. Code that works around this probably-nonexistent bug should be reconsidered (especially since Postbox support is dropped). it('Range.intersectsNode is broken on Chrome', function() { const range = document.createRange(); range.selectNode(document.getElementById('test-elem-1')); if (typeof(window.chrome) !== 'undefined' && navigator.userAgent.indexOf('Chrome') >= 0) { expect(range.intersectsNode(document.getElementById('test-elem-2'))).to.be.true; } }); }); });
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
false
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/common/test/underscore.js
src/common/test/underscore.js
// Underscore.js 1.4.4 // http://underscorejs.org // (c) 2009-2013 Jeremy Ashkenas, DocumentCloud Inc. // Underscore may be freely distributed under the MIT license. (function() { // Baseline setup // -------------- // Establish the root object, `window` in the browser, or `global` on the server. var root = this; // Save the previous value of the `_` variable. var previousUnderscore = root._; // Establish the object that gets returned to break out of a loop iteration. var breaker = {}; // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; // Create quick reference variables for speed access to core prototypes. var push = ArrayProto.push, slice = ArrayProto.slice, concat = ArrayProto.concat, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // All **ECMAScript 5** native function implementations that we hope to use // are declared here. var nativeForEach = ArrayProto.forEach, nativeMap = ArrayProto.map, nativeReduce = ArrayProto.reduce, nativeReduceRight = ArrayProto.reduceRight, nativeFilter = ArrayProto.filter, nativeEvery = ArrayProto.every, nativeSome = ArrayProto.some, nativeIndexOf = ArrayProto.indexOf, nativeLastIndexOf = ArrayProto.lastIndexOf, nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeBind = FuncProto.bind; // Create a safe reference to the Underscore object for use below. var _ = function(obj) { if (obj instanceof _) return obj; if (!(this instanceof _)) return new _(obj); this._wrapped = obj; }; // Export the Underscore object for **Node.js**, with // backwards-compatibility for the old `require()` API. If we're in // the browser, add `_` as a global object via a string identifier, // for Closure Compiler "advanced" mode. if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = _; } exports._ = _; } else { root._ = _; } // Current version. _.VERSION = '1.4.4'; // Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `forEach`. // Handles objects with the built-in `forEach`, arrays, and raw objects. // Delegates to **ECMAScript 5**'s native `forEach` if available. var each = _.each = _.forEach = function(obj, iterator, context) { if (obj == null) return; if (nativeForEach && obj.forEach === nativeForEach) { obj.forEach(iterator, context); } else if (obj.length === +obj.length) { for (var i = 0, l = obj.length; i < l; i++) { if (iterator.call(context, obj[i], i, obj) === breaker) return; } } else { for (var key in obj) { if (_.has(obj, key)) { if (iterator.call(context, obj[key], key, obj) === breaker) return; } } } }; // Return the results of applying the iterator to each element. // Delegates to **ECMAScript 5**'s native `map` if available. _.map = _.collect = function(obj, iterator, context) { var results = []; if (obj == null) return results; if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); each(obj, function(value, index, list) { results[results.length] = iterator.call(context, value, index, list); }); return results; }; var reduceError = 'Reduce of empty array with no initial value'; // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { var initial = arguments.length > 2; if (obj == null) obj = []; if (nativeReduce && obj.reduce === nativeReduce) { if (context) iterator = _.bind(iterator, context); return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); } each(obj, function(value, index, list) { if (!initial) { memo = value; initial = true; } else { memo = iterator.call(context, memo, value, index, list); } }); if (!initial) throw new TypeError(reduceError); return memo; }; // The right-associative version of reduce, also known as `foldr`. // Delegates to **ECMAScript 5**'s native `reduceRight` if available. _.reduceRight = _.foldr = function(obj, iterator, memo, context) { var initial = arguments.length > 2; if (obj == null) obj = []; if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { if (context) iterator = _.bind(iterator, context); return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); } var length = obj.length; if (length !== +length) { var keys = _.keys(obj); length = keys.length; } each(obj, function(value, index, list) { index = keys ? keys[--length] : --length; if (!initial) { memo = obj[index]; initial = true; } else { memo = iterator.call(context, memo, obj[index], index, list); } }); if (!initial) throw new TypeError(reduceError); return memo; }; // Return the first value which passes a truth test. Aliased as `detect`. _.find = _.detect = function(obj, iterator, context) { var result; any(obj, function(value, index, list) { if (iterator.call(context, value, index, list)) { result = value; return true; } }); return result; }; // Return all the elements that pass a truth test. // Delegates to **ECMAScript 5**'s native `filter` if available. // Aliased as `select`. _.filter = _.select = function(obj, iterator, context) { var results = []; if (obj == null) return results; if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context); each(obj, function(value, index, list) { if (iterator.call(context, value, index, list)) results[results.length] = value; }); return results; }; // Return all the elements for which a truth test fails. _.reject = function(obj, iterator, context) { return _.filter(obj, function(value, index, list) { return !iterator.call(context, value, index, list); }, context); }; // Determine whether all of the elements match a truth test. // Delegates to **ECMAScript 5**'s native `every` if available. // Aliased as `all`. _.every = _.all = function(obj, iterator, context) { iterator || (iterator = _.identity); var result = true; if (obj == null) return result; if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context); each(obj, function(value, index, list) { if (!(result = result && iterator.call(context, value, index, list))) return breaker; }); return !!result; }; // Determine if at least one element in the object matches a truth test. // Delegates to **ECMAScript 5**'s native `some` if available. // Aliased as `any`. var any = _.some = _.any = function(obj, iterator, context) { iterator || (iterator = _.identity); var result = false; if (obj == null) return result; if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); each(obj, function(value, index, list) { if (result || (result = iterator.call(context, value, index, list))) return breaker; }); return !!result; }; // Determine if the array or object contains a given value (using `===`). // Aliased as `include`. _.contains = _.include = function(obj, target) { if (obj == null) return false; if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; return any(obj, function(value) { return value === target; }); }; // Invoke a method (with arguments) on every item in a collection. _.invoke = function(obj, method) { var args = slice.call(arguments, 2); var isFunc = _.isFunction(method); return _.map(obj, function(value) { return (isFunc ? method : value[method]).apply(value, args); }); }; // Convenience version of a common use case of `map`: fetching a property. _.pluck = function(obj, key) { return _.map(obj, function(value){ return value[key]; }); }; // Convenience version of a common use case of `filter`: selecting only objects // containing specific `key:value` pairs. _.where = function(obj, attrs, first) { if (_.isEmpty(attrs)) return first ? null : []; return _[first ? 'find' : 'filter'](obj, function(value) { for (var key in attrs) { if (attrs[key] !== value[key]) return false; } return true; }); }; // Convenience version of a common use case of `find`: getting the first object // containing specific `key:value` pairs. _.findWhere = function(obj, attrs) { return _.where(obj, attrs, true); }; // Return the maximum element or (element-based computation). // Can't optimize arrays of integers longer than 65,535 elements. // See: https://bugs.webkit.org/show_bug.cgi?id=80797 _.max = function(obj, iterator, context) { if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { return Math.max.apply(Math, obj); } if (!iterator && _.isEmpty(obj)) return -Infinity; var result = {computed : -Infinity, value: -Infinity}; each(obj, function(value, index, list) { var computed = iterator ? iterator.call(context, value, index, list) : value; computed >= result.computed && (result = {value : value, computed : computed}); }); return result.value; }; // Return the minimum element (or element-based computation). _.min = function(obj, iterator, context) { if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { return Math.min.apply(Math, obj); } if (!iterator && _.isEmpty(obj)) return Infinity; var result = {computed : Infinity, value: Infinity}; each(obj, function(value, index, list) { var computed = iterator ? iterator.call(context, value, index, list) : value; computed < result.computed && (result = {value : value, computed : computed}); }); return result.value; }; // Shuffle an array. _.shuffle = function(obj) { var rand; var index = 0; var shuffled = []; each(obj, function(value) { rand = _.random(index++); shuffled[index - 1] = shuffled[rand]; shuffled[rand] = value; }); return shuffled; }; // An internal function to generate lookup iterators. var lookupIterator = function(value) { return _.isFunction(value) ? value : function(obj){ return obj[value]; }; }; // Sort the object's values by a criterion produced by an iterator. _.sortBy = function(obj, value, context) { var iterator = lookupIterator(value); return _.pluck(_.map(obj, function(value, index, list) { return { value : value, index : index, criteria : iterator.call(context, value, index, list) }; }).sort(function(left, right) { var a = left.criteria; var b = right.criteria; if (a !== b) { if (a > b || a === void 0) return 1; if (a < b || b === void 0) return -1; } return left.index < right.index ? -1 : 1; }), 'value'); }; // An internal function used for aggregate "group by" operations. var group = function(obj, value, context, behavior) { var result = {}; var iterator = lookupIterator(value || _.identity); each(obj, function(value, index) { var key = iterator.call(context, value, index, obj); behavior(result, key, value); }); return result; }; // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. _.groupBy = function(obj, value, context) { return group(obj, value, context, function(result, key, value) { (_.has(result, key) ? result[key] : (result[key] = [])).push(value); }); }; // Counts instances of an object that group by a certain criterion. Pass // either a string attribute to count by, or a function that returns the // criterion. _.countBy = function(obj, value, context) { return group(obj, value, context, function(result, key) { if (!_.has(result, key)) result[key] = 0; result[key]++; }); }; // Use a comparator function to figure out the smallest index at which // an object should be inserted so as to maintain order. Uses binary search. _.sortedIndex = function(array, obj, iterator, context) { iterator = iterator == null ? _.identity : lookupIterator(iterator); var value = iterator.call(context, obj); var low = 0, high = array.length; while (low < high) { var mid = (low + high) >>> 1; iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid; } return low; }; // Safely convert anything iterable into a real, live array. _.toArray = function(obj) { if (!obj) return []; if (_.isArray(obj)) return slice.call(obj); if (obj.length === +obj.length) return _.map(obj, _.identity); return _.values(obj); }; // Return the number of elements in an object. _.size = function(obj) { if (obj == null) return 0; return (obj.length === +obj.length) ? obj.length : _.keys(obj).length; }; // Array Functions // --------------- // Get the first element of an array. Passing **n** will return the first N // values in the array. Aliased as `head` and `take`. The **guard** check // allows it to work with `_.map`. _.first = _.head = _.take = function(array, n, guard) { if (array == null) return void 0; return (n != null) && !guard ? slice.call(array, 0, n) : array[0]; }; // Returns everything but the last entry of the array. Especially useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. The **guard** check allows it to work with // `_.map`. _.initial = function(array, n, guard) { return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); }; // Get the last element of an array. Passing **n** will return the last N // values in the array. The **guard** check allows it to work with `_.map`. _.last = function(array, n, guard) { if (array == null) return void 0; if ((n != null) && !guard) { return slice.call(array, Math.max(array.length - n, 0)); } else { return array[array.length - 1]; } }; // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. // Especially useful on the arguments object. Passing an **n** will return // the rest N values in the array. The **guard** // check allows it to work with `_.map`. _.rest = _.tail = _.drop = function(array, n, guard) { return slice.call(array, (n == null) || guard ? 1 : n); }; // Trim out all falsy values from an array. _.compact = function(array) { return _.filter(array, _.identity); }; // Internal implementation of a recursive `flatten` function. var flatten = function(input, shallow, output) { each(input, function(value) { if (_.isArray(value)) { shallow ? push.apply(output, value) : flatten(value, shallow, output); } else { output.push(value); } }); return output; }; // Return a completely flattened version of an array. _.flatten = function(array, shallow) { return flatten(array, shallow, []); }; // Return a version of the array that does not contain the specified value(s). _.without = function(array) { return _.difference(array, slice.call(arguments, 1)); }; // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // Aliased as `unique`. _.uniq = _.unique = function(array, isSorted, iterator, context) { if (_.isFunction(isSorted)) { context = iterator; iterator = isSorted; isSorted = false; } var initial = iterator ? _.map(array, iterator, context) : array; var results = []; var seen = []; each(initial, function(value, index) { if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) { seen.push(value); results.push(array[index]); } }); return results; }; // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. _.union = function() { return _.uniq(concat.apply(ArrayProto, arguments)); }; // Produce an array that contains every item shared between all the // passed-in arrays. _.intersection = function(array) { var rest = slice.call(arguments, 1); return _.filter(_.uniq(array), function(item) { return _.every(rest, function(other) { return _.indexOf(other, item) >= 0; }); }); }; // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. _.difference = function(array) { var rest = concat.apply(ArrayProto, slice.call(arguments, 1)); return _.filter(array, function(value){ return !_.contains(rest, value); }); }; // Zip together multiple lists into a single array -- elements that share // an index go together. _.zip = function() { var args = slice.call(arguments); var length = _.max(_.pluck(args, 'length')); var results = new Array(length); for (var i = 0; i < length; i++) { results[i] = _.pluck(args, "" + i); } return results; }; // Converts lists into objects. Pass either a single array of `[key, value]` // pairs, or two parallel arrays of the same length -- one of keys, and one of // the corresponding values. _.object = function(list, values) { if (list == null) return {}; var result = {}; for (var i = 0, l = list.length; i < l; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; }; // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), // we need this function. Return the position of the first occurrence of an // item in an array, or -1 if the item is not included in the array. // Delegates to **ECMAScript 5**'s native `indexOf` if available. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. _.indexOf = function(array, item, isSorted) { if (array == null) return -1; var i = 0, l = array.length; if (isSorted) { if (typeof isSorted == 'number') { i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted); } else { i = _.sortedIndex(array, item); return array[i] === item ? i : -1; } } if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted); for (; i < l; i++) if (array[i] === item) return i; return -1; }; // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. _.lastIndexOf = function(array, item, from) { if (array == null) return -1; var hasIndex = from != null; if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) { return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item); } var i = (hasIndex ? from : array.length); while (i--) if (array[i] === item) return i; return -1; }; // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](http://docs.python.org/library/functions.html#range). _.range = function(start, stop, step) { if (arguments.length <= 1) { stop = start || 0; start = 0; } step = arguments[2] || 1; var len = Math.max(Math.ceil((stop - start) / step), 0); var idx = 0; var range = new Array(len); while(idx < len) { range[idx++] = start; start += step; } return range; }; // Function (ahem) Functions // ------------------ // Create a function bound to a given object (assigning `this`, and arguments, // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if // available. _.bind = function(func, context) { if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); var args = slice.call(arguments, 2); return function() { return func.apply(context, args.concat(slice.call(arguments))); }; }; // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. _.partial = function(func) { var args = slice.call(arguments, 1); return function() { return func.apply(this, args.concat(slice.call(arguments))); }; }; // Bind all of an object's methods to that object. Useful for ensuring that // all callbacks defined on an object belong to it. _.bindAll = function(obj) { var funcs = slice.call(arguments, 1); if (funcs.length === 0) funcs = _.functions(obj); each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); return obj; }; // Memoize an expensive function by storing its results. _.memoize = function(func, hasher) { var memo = {}; hasher || (hasher = _.identity); return function() { var key = hasher.apply(this, arguments); return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); }; }; // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. _.delay = function(func, wait) { var args = slice.call(arguments, 2); return setTimeout(function(){ return func.apply(null, args); }, wait); }; // Defers a function, scheduling it to run after the current call stack has // cleared. _.defer = function(func) { return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); }; // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. _.throttle = function(func, wait) { var context, args, timeout, result; var previous = 0; var later = function() { previous = new Date; timeout = null; result = func.apply(context, args); }; return function() { var now = new Date; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); } else if (!timeout) { timeout = setTimeout(later, remaining); } return result; }; }; // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. _.debounce = function(func, wait, immediate) { var timeout, result; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) result = func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) result = func.apply(context, args); return result; }; }; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. _.once = function(func) { var ran = false, memo; return function() { if (ran) return memo; ran = true; memo = func.apply(this, arguments); func = null; return memo; }; }; // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. _.wrap = function(func, wrapper) { return function() { var args = [func]; push.apply(args, arguments); return wrapper.apply(this, args); }; }; // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. _.compose = function() { var funcs = arguments; return function() { var args = arguments; for (var i = funcs.length - 1; i >= 0; i--) { args = [funcs[i].apply(this, args)]; } return args[0]; }; }; // Returns a function that will only be executed after being called N times. _.after = function(times, func) { if (times <= 0) return func(); return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; // Object Functions // ---------------- // Retrieve the names of an object's properties. // Delegates to **ECMAScript 5**'s native `Object.keys` _.keys = nativeKeys || function(obj) { if (obj !== Object(obj)) throw new TypeError('Invalid object'); var keys = []; for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key; return keys; }; // Retrieve the values of an object's properties. _.values = function(obj) { var values = []; for (var key in obj) if (_.has(obj, key)) values.push(obj[key]); return values; }; // Convert an object into a list of `[key, value]` pairs. _.pairs = function(obj) { var pairs = []; for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]); return pairs; }; // Invert the keys and values of an object. The values must be serializable. _.invert = function(obj) { var result = {}; for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key; return result; }; // Return a sorted list of the function names available on the object. // Aliased as `methods` _.functions = _.methods = function(obj) { var names = []; for (var key in obj) { if (_.isFunction(obj[key])) names.push(key); } return names.sort(); }; // Extend a given object with all the properties in passed-in object(s). _.extend = function(obj) { each(slice.call(arguments, 1), function(source) { if (source) { for (var prop in source) { obj[prop] = source[prop]; } } }); return obj; }; // Return a copy of the object only containing the whitelisted properties. _.pick = function(obj) { var copy = {}; var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); each(keys, function(key) { if (key in obj) copy[key] = obj[key]; }); return copy; }; // Return a copy of the object without the blacklisted properties. _.omit = function(obj) { var copy = {}; var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); for (var key in obj) { if (!_.contains(keys, key)) copy[key] = obj[key]; } return copy; }; // Fill in a given object with default properties. _.defaults = function(obj) { each(slice.call(arguments, 1), function(source) { if (source) { for (var prop in source) { if (obj[prop] == null) obj[prop] = source[prop]; } } }); return obj; }; // Create a (shallow-cloned) duplicate of an object. _.clone = function(obj) { if (!_.isObject(obj)) return obj; return _.isArray(obj) ? obj.slice() : _.extend({}, obj); }; // Invokes interceptor with the obj, and then returns obj. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. _.tap = function(obj, interceptor) { interceptor(obj); return obj; }; // Internal recursive comparison function for `isEqual`. var eq = function(a, b, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal. if (a === b) return a !== 0 || 1 / a == 1 / b; // A strict comparison is necessary because `null == undefined`. if (a == null || b == null) return a === b; // Unwrap any wrapped objects. if (a instanceof _) a = a._wrapped; if (b instanceof _) b = b._wrapped; // Compare `[[Class]]` names. var className = toString.call(a); if (className != toString.call(b)) return false; switch (className) { // Strings, numbers, dates, and booleans are compared by value. case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return a == String(b); case '[object Number]': // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for // other numeric values. return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a == +b; // RegExps are compared by their source patterns and flags. case '[object RegExp]': return a.source == b.source && a.global == b.global && a.multiline == b.multiline && a.ignoreCase == b.ignoreCase; } if (typeof a != 'object' || typeof b != 'object') return false; // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] == a) return bStack[length] == b; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); var size = 0, result = true; // Recursively compare objects and arrays. if (className == '[object Array]') { // Compare array lengths to determine if a deep comparison is necessary. size = a.length; result = size == b.length; if (result) { // Deep compare the contents, ignoring non-numeric properties. while (size--) { if (!(result = eq(a[size], b[size], aStack, bStack))) break; } } } else { // Objects with different constructors are not equivalent, but `Object`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) && _.isFunction(bCtor) && (bCtor instanceof bCtor))) { return false; } // Deep compare objects. for (var key in a) { if (_.has(a, key)) { // Count the expected number of properties. size++; // Deep compare each member. if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break; } } // Ensure that both objects contain the same number of properties. if (result) { for (key in b) { if (_.has(b, key) && !(size--)) break; } result = !size; } } // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); return result; }; // Perform a deep comparison to check if two objects are equal. _.isEqual = function(a, b) { return eq(a, b, [], []); }; // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. _.isEmpty = function(obj) { if (obj == null) return true; if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; for (var key in obj) if (_.has(obj, key)) return false; return true; }; // Is a given value a DOM element? _.isElement = function(obj) { return !!(obj && obj.nodeType === 1); }; // Is a given value an array? // Delegates to ECMA5's native Array.isArray _.isArray = nativeIsArray || function(obj) { return toString.call(obj) == '[object Array]'; };
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
true
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/common/test/markdown-here-test.js
src/common/test/markdown-here-test.js
/* * Copyright Adam Pritchard 2013 * MIT License : https://adampritchard.mit-license.org/ */ "use strict"; /* jshint curly:true, noempty:true, newcap:true, eqeqeq:true, eqnull:true, undef:true, devel:true, browser:true, node:true, evil:false, latedef:false, nonew:true, trailing:false, immed:false, smarttabs:true, expr:true */ /* global describe, expect, it, before, beforeEach, after, afterEach */ /* global _, MarkdownRender, htmlToText, marked, hljs, Utils, MdhHtmlToText, markdownHere */ // TODO: Lots more tests. describe('markdownHere', function() { it('should exist', function() { expect(markdownHere).to.exist; }); it('platform supports MutationObserver', function() { expect(window.MutationObserver || window.WebKitMutationObserver).to.be.ok; }); describe('markdownHere', function() { let userprefs = {}; let testElem = null; beforeEach(function() { userprefs = { 'math-value': null, 'math-enabled': false, 'main-css': '', 'syntax-css': '' }; testElem = document.createElement('div'); testElem.contentEditable = 'true'; document.body.appendChild(testElem); }); afterEach(function() { if (testElem && testElem.parentNode) { testElem.parentNode.removeChild(testElem); } }); var markdownRenderHelper = function(elem, range, callback) { var mdhHtmlToText = new MdhHtmlToText.MdhHtmlToText(elem, range); var renderedMarkdown = MarkdownRender.markdownRender( mdhHtmlToText.get(), userprefs, marked, hljs); renderedMarkdown = mdhHtmlToText.postprocess(renderedMarkdown); callback(renderedMarkdown, userprefs['main-css'] + userprefs['syntax-css']); }; var renderMD = function(mdHTML, renderCompleteCallback) { Utils.saferSetInnerHTML(testElem, mdHTML); testElem.focus(); renderFocusedElem(renderCompleteCallback); }; var renderFocusedElem = function(renderCompleteCallback) { markdownHere( document, markdownRenderHelper, function() { console.log.apply(console, arguments); }, renderCompleteCallback); }; // If there's no error, done has to be called with no argument. var doneCaller = function(expectedInnerHtml, done) { expectedInnerHtml = expectedInnerHtml.trim(); return function(elem) { var renderedHTMLRegex = /^<div class="markdown-here-wrapper" data-md-url="[^"]+">([\s\S]*)<div title="MDH:[\s\S]+">[\s\S]*<\/div><\/div>$/; var renderedHTML = elem.innerHTML.match(renderedHTMLRegex)[1]; renderedHTML = renderedHTML.trim(); expect(renderedHTML).to.equal(expectedInnerHtml); done(); }; }; it('should render simple MD', function(done) { var md = '_hi_'; var html = '<p><em>hi</em></p>'; renderMD(md, doneCaller(html, done)); }); it('should unrender simple MD', function(done) { var md = '_hi_'; // First render renderMD(md, function(elem) { // Then unrender testElem.focus(); renderFocusedElem( function(elem) { expect(elem.innerHTML).to.equal(md); done(); }); }); }); // Tests fix for https://github.com/adam-p/markdown-here/issues/297 // Attempting to unrender an email that was a reply to an email that was // itself MDH-rendered failed. it('should unrender a reply to a rendered email', function(done) { var replyMD = '_bye_'; var fullReplyMD = replyMD+'<br><div class="gmail_quote">On Fri, Aug 14, 2015 at 10:34 PM, Billy Bob <span dir="ltr">&lt;<a href="mailto:bb@example.com" target="_blank">bb@example.com</a>&gt;</span> wrote:<br><blockquote><div class="markdown-here-wrapper" data-md-url="xxx"><p><em>hi</em></p>\n<div title="MDH:X2hpXw==" style="height:0;width:0;max-height:0;max-width:0;overflow:hidden;font-size:0em;padding:0;margin:0;">​</div></div></blockquote></div>'; // First render renderMD(fullReplyMD, function(elem) { // Then unrender testElem.focus(); renderFocusedElem( function(elem) { expect(elem.innerHTML.slice(0, replyMD.length)).to.equal(replyMD); done(); }); }); }); }); });
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
false
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/common/test/mocha.js
src/common/test/mocha.js
;(function(){ // CommonJS require() function require(p){ var path = require.resolve(p) , mod = require.modules[path]; if (!mod) throw new Error('failed to require "' + p + '"'); if (!mod.exports) { mod.exports = {}; mod.call(mod.exports, mod, mod.exports, require.relative(path)); } return mod.exports; } require.modules = {}; require.resolve = function (path){ var orig = path , reg = path + '.js' , index = path + '/index.js'; return require.modules[reg] && reg || require.modules[index] && index || orig; }; require.register = function (path, fn){ require.modules[path] = fn; }; require.relative = function (parent) { return function(p){ if ('.' != p.charAt(0)) return require(p); var path = parent.split('/') , segs = p.split('/'); path.pop(); for (var i = 0; i < segs.length; i++) { var seg = segs[i]; if ('..' == seg) path.pop(); else if ('.' != seg) path.push(seg); } return require(path.join('/')); }; }; require.register("browser/debug.js", function(module, exports, require){ module.exports = function(type){ return function(){ } }; }); // module: browser/debug.js require.register("browser/diff.js", function(module, exports, require){ /* See license.txt for terms of usage */ /* * Text diff implementation. * * This library supports the following APIS: * JsDiff.diffChars: Character by character diff * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace * JsDiff.diffLines: Line based diff * * JsDiff.diffCss: Diff targeted at CSS content * * These methods are based on the implementation proposed in * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 */ var JsDiff = (function() { function clonePath(path) { return { newPos: path.newPos, components: path.components.slice(0) }; } function removeEmpty(array) { var ret = []; for (var i = 0; i < array.length; i++) { if (array[i]) { ret.push(array[i]); } } return ret; } function escapeHTML(s) { var n = s; n = n.replace(/&/g, "&amp;"); n = n.replace(/</g, "&lt;"); n = n.replace(/>/g, "&gt;"); n = n.replace(/"/g, "&quot;"); return n; } var fbDiff = function(ignoreWhitespace) { this.ignoreWhitespace = ignoreWhitespace; }; fbDiff.prototype = { diff: function(oldString, newString) { // Handle the identity case (this is due to unrolling editLength == 0 if (newString == oldString) { return [{ value: newString }]; } if (!newString) { return [{ value: oldString, removed: true }]; } if (!oldString) { return [{ value: newString, added: true }]; } newString = this.tokenize(newString); oldString = this.tokenize(oldString); var newLen = newString.length, oldLen = oldString.length; var maxEditLength = newLen + oldLen; var bestPath = [{ newPos: -1, components: [] }]; // Seed editLength = 0 var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) { return bestPath[0].components; } for (var editLength = 1; editLength <= maxEditLength; editLength++) { for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) { var basePath; var addPath = bestPath[diagonalPath-1], removePath = bestPath[diagonalPath+1]; oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; if (addPath) { // No one else is going to attempt to use this value, clear it bestPath[diagonalPath-1] = undefined; } var canAdd = addPath && addPath.newPos+1 < newLen; var canRemove = removePath && 0 <= oldPos && oldPos < oldLen; if (!canAdd && !canRemove) { bestPath[diagonalPath] = undefined; continue; } // Select the diagonal that we want to branch from. We select the prior // path whose position in the new string is the farthest from the origin // and does not pass the bounds of the diff graph if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) { basePath = clonePath(removePath); this.pushComponent(basePath.components, oldString[oldPos], undefined, true); } else { basePath = clonePath(addPath); basePath.newPos++; this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined); } var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath); if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) { return basePath.components; } else { bestPath[diagonalPath] = basePath; } } } }, pushComponent: function(components, value, added, removed) { var last = components[components.length-1]; if (last && last.added === added && last.removed === removed) { // We need to clone here as the component clone operation is just // as shallow array clone components[components.length-1] = {value: this.join(last.value, value), added: added, removed: removed }; } else { components.push({value: value, added: added, removed: removed }); } }, extractCommon: function(basePath, newString, oldString, diagonalPath) { var newLen = newString.length, oldLen = oldString.length, newPos = basePath.newPos, oldPos = newPos - diagonalPath; while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) { newPos++; oldPos++; this.pushComponent(basePath.components, newString[newPos], undefined, undefined); } basePath.newPos = newPos; return oldPos; }, equals: function(left, right) { var reWhitespace = /\S/; if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) { return true; } else { return left == right; } }, join: function(left, right) { return left + right; }, tokenize: function(value) { return value; } }; var CharDiff = new fbDiff(); var WordDiff = new fbDiff(true); WordDiff.tokenize = function(value) { return removeEmpty(value.split(/(\s+|\b)/)); }; var CssDiff = new fbDiff(true); CssDiff.tokenize = function(value) { return removeEmpty(value.split(/([{}:;,]|\s+)/)); }; var LineDiff = new fbDiff(); LineDiff.tokenize = function(value) { return value.split(/^/m); }; return { diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); }, diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); }, diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); }, diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); }, createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) { var ret = []; ret.push("Index: " + fileName); ret.push("==================================================================="); ret.push("--- " + fileName + (typeof oldHeader === "undefined" ? "" : "\t" + oldHeader)); ret.push("+++ " + fileName + (typeof newHeader === "undefined" ? "" : "\t" + newHeader)); var diff = LineDiff.diff(oldStr, newStr); if (!diff[diff.length-1].value) { diff.pop(); // Remove trailing newline add } diff.push({value: "", lines: []}); // Append an empty value to make cleanup easier function contextLines(lines) { return lines.map(function(entry) { return ' ' + entry; }); } function eofNL(curRange, i, current) { var last = diff[diff.length-2], isLast = i === diff.length-2, isLastOfType = i === diff.length-3 && (current.added === !last.added || current.removed === !last.removed); // Figure out if this is the last line for the given file and missing NL if (!/\n$/.test(current.value) && (isLast || isLastOfType)) { curRange.push('\\ No newline at end of file'); } } var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; for (var i = 0; i < diff.length; i++) { var current = diff[i], lines = current.lines || current.value.replace(/\n$/, "").split("\n"); current.lines = lines; if (current.added || current.removed) { if (!oldRangeStart) { var prev = diff[i-1]; oldRangeStart = oldLine; newRangeStart = newLine; if (prev) { curRange = contextLines(prev.lines.slice(-4)); oldRangeStart -= curRange.length; newRangeStart -= curRange.length; } } curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?"+":"-") + entry; })); eofNL(curRange, i, current); if (current.added) { newLine += lines.length; } else { oldLine += lines.length; } } else { if (oldRangeStart) { // Close out any changes that have been output (or join overlapping) if (lines.length <= 8 && i < diff.length-2) { // Overlapping curRange.push.apply(curRange, contextLines(lines)); } else { // end the range and output var contextSize = Math.min(lines.length, 4); ret.push( "@@ -" + oldRangeStart + "," + (oldLine-oldRangeStart+contextSize) + " +" + newRangeStart + "," + (newLine-newRangeStart+contextSize) + " @@"); ret.push.apply(ret, curRange); ret.push.apply(ret, contextLines(lines.slice(0, contextSize))); if (lines.length <= 4) { eofNL(ret, i, current); } oldRangeStart = 0; newRangeStart = 0; curRange = []; } } oldLine += lines.length; newLine += lines.length; } } return ret.join('\n') + '\n'; }, convertChangesToXML: function(changes){ var ret = []; for ( var i = 0; i < changes.length; i++) { var change = changes[i]; if (change.added) { ret.push("<ins>"); } else if (change.removed) { ret.push("<del>"); } ret.push(escapeHTML(change.value)); if (change.added) { ret.push("</ins>"); } else if (change.removed) { ret.push("</del>"); } } return ret.join(""); } }; })(); if (typeof module !== "undefined") { module.exports = JsDiff; } }); // module: browser/diff.js require.register("browser/events.js", function(module, exports, require){ /** * Module exports. */ exports.EventEmitter = EventEmitter; /** * Check if `obj` is an array. */ function isArray(obj) { return '[object Array]' == {}.toString.call(obj); } /** * Event emitter constructor. * * @api public */ function EventEmitter(){}; /** * Adds a listener. * * @api public */ EventEmitter.prototype.on = function (name, fn) { if (!this.$events) { this.$events = {}; } if (!this.$events[name]) { this.$events[name] = fn; } else if (isArray(this.$events[name])) { this.$events[name].push(fn); } else { this.$events[name] = [this.$events[name], fn]; } return this; }; EventEmitter.prototype.addListener = EventEmitter.prototype.on; /** * Adds a volatile listener. * * @api public */ EventEmitter.prototype.once = function (name, fn) { var self = this; function on () { self.removeListener(name, on); fn.apply(this, arguments); }; on.listener = fn; this.on(name, on); return this; }; /** * Removes a listener. * * @api public */ EventEmitter.prototype.removeListener = function (name, fn) { if (this.$events && this.$events[name]) { var list = this.$events[name]; if (isArray(list)) { var pos = -1; for (var i = 0, l = list.length; i < l; i++) { if (list[i] === fn || (list[i].listener && list[i].listener === fn)) { pos = i; break; } } if (pos < 0) { return this; } list.splice(pos, 1); if (!list.length) { delete this.$events[name]; } } else if (list === fn || (list.listener && list.listener === fn)) { delete this.$events[name]; } } return this; }; /** * Removes all listeners for an event. * * @api public */ EventEmitter.prototype.removeAllListeners = function (name) { if (name === undefined) { this.$events = {}; return this; } if (this.$events && this.$events[name]) { this.$events[name] = null; } return this; }; /** * Gets all listeners for a certain event. * * @api public */ EventEmitter.prototype.listeners = function (name) { if (!this.$events) { this.$events = {}; } if (!this.$events[name]) { this.$events[name] = []; } if (!isArray(this.$events[name])) { this.$events[name] = [this.$events[name]]; } return this.$events[name]; }; /** * Emits an event. * * @api public */ EventEmitter.prototype.emit = function (name) { if (!this.$events) { return false; } var handler = this.$events[name]; if (!handler) { return false; } var args = [].slice.call(arguments, 1); if ('function' == typeof handler) { handler.apply(this, args); } else if (isArray(handler)) { var listeners = handler.slice(); for (var i = 0, l = listeners.length; i < l; i++) { listeners[i].apply(this, args); } } else { return false; } return true; }; }); // module: browser/events.js require.register("browser/fs.js", function(module, exports, require){ }); // module: browser/fs.js require.register("browser/path.js", function(module, exports, require){ }); // module: browser/path.js require.register("browser/progress.js", function(module, exports, require){ /** * Expose `Progress`. */ module.exports = Progress; /** * Initialize a new `Progress` indicator. */ function Progress() { this.percent = 0; this.size(0); this.fontSize(11); this.font('helvetica, arial, sans-serif'); } /** * Set progress size to `n`. * * @param {Number} n * @return {Progress} for chaining * @api public */ Progress.prototype.size = function(n){ this._size = n; return this; }; /** * Set text to `str`. * * @param {String} str * @return {Progress} for chaining * @api public */ Progress.prototype.text = function(str){ this._text = str; return this; }; /** * Set font size to `n`. * * @param {Number} n * @return {Progress} for chaining * @api public */ Progress.prototype.fontSize = function(n){ this._fontSize = n; return this; }; /** * Set font `family`. * * @param {String} family * @return {Progress} for chaining */ Progress.prototype.font = function(family){ this._font = family; return this; }; /** * Update percentage to `n`. * * @param {Number} n * @return {Progress} for chaining */ Progress.prototype.update = function(n){ this.percent = n; return this; }; /** * Draw on `ctx`. * * @param {CanvasRenderingContext2d} ctx * @return {Progress} for chaining */ Progress.prototype.draw = function(ctx){ var percent = Math.min(this.percent, 100) , size = this._size , half = size / 2 , x = half , y = half , rad = half - 1 , fontSize = this._fontSize; ctx.font = fontSize + 'px ' + this._font; var angle = Math.PI * 2 * (percent / 100); ctx.clearRect(0, 0, size, size); // outer circle ctx.strokeStyle = '#9f9f9f'; ctx.beginPath(); ctx.arc(x, y, rad, 0, angle, false); ctx.stroke(); // inner circle ctx.strokeStyle = '#eee'; ctx.beginPath(); ctx.arc(x, y, rad - 1, 0, angle, true); ctx.stroke(); // text var text = this._text || (percent | 0) + '%' , w = ctx.measureText(text).width; ctx.fillText( text , x - w / 2 + 1 , y + fontSize / 2 - 1); return this; }; }); // module: browser/progress.js require.register("browser/tty.js", function(module, exports, require){ exports.isatty = function(){ return true; }; exports.getWindowSize = function(){ return [window.innerHeight, window.innerWidth]; }; }); // module: browser/tty.js require.register("context.js", function(module, exports, require){ /** * Expose `Context`. */ module.exports = Context; /** * Initialize a new `Context`. * * @api private */ function Context(){} /** * Set or get the context `Runnable` to `runnable`. * * @param {Runnable} runnable * @return {Context} * @api private */ Context.prototype.runnable = function(runnable){ if (0 == arguments.length) return this._runnable; this.test = this._runnable = runnable; return this; }; /** * Set test timeout `ms`. * * @param {Number} ms * @return {Context} self * @api private */ Context.prototype.timeout = function(ms){ this.runnable().timeout(ms); return this; }; /** * Set test slowness threshold `ms`. * * @param {Number} ms * @return {Context} self * @api private */ Context.prototype.slow = function(ms){ this.runnable().slow(ms); return this; }; /** * Inspect the context void of `._runnable`. * * @return {String} * @api private */ Context.prototype.inspect = function(){ return JSON.stringify(this, function(key, val){ if ('_runnable' == key) return; if ('test' == key) return; return val; }, 2); }; }); // module: context.js require.register("hook.js", function(module, exports, require){ /** * Module dependencies. */ var Runnable = require('./runnable'); /** * Expose `Hook`. */ module.exports = Hook; /** * Initialize a new `Hook` with the given `title` and callback `fn`. * * @param {String} title * @param {Function} fn * @api private */ function Hook(title, fn) { Runnable.call(this, title, fn); this.type = 'hook'; } /** * Inherit from `Runnable.prototype`. */ function F(){}; F.prototype = Runnable.prototype; Hook.prototype = new F; Hook.prototype.constructor = Hook; /** * Get or set the test `err`. * * @param {Error} err * @return {Error} * @api public */ Hook.prototype.error = function(err){ if (0 == arguments.length) { var err = this._error; this._error = null; return err; } this._error = err; }; }); // module: hook.js require.register("interfaces/bdd.js", function(module, exports, require){ /** * Module dependencies. */ var Suite = require('../suite') , Test = require('../test'); /** * BDD-style interface: * * describe('Array', function(){ * describe('#indexOf()', function(){ * it('should return -1 when not present', function(){ * * }); * * it('should return the index when present', function(){ * * }); * }); * }); * */ module.exports = function(suite){ var suites = [suite]; suite.on('pre-require', function(context, file, mocha){ /** * Execute before running tests. */ context.before = function(fn){ suites[0].beforeAll(fn); }; /** * Execute after running tests. */ context.after = function(fn){ suites[0].afterAll(fn); }; /** * Execute before each test case. */ context.beforeEach = function(fn){ suites[0].beforeEach(fn); }; /** * Execute after each test case. */ context.afterEach = function(fn){ suites[0].afterEach(fn); }; /** * Describe a "suite" with the given `title` * and callback `fn` containing nested suites * and/or tests. */ context.describe = context.context = function(title, fn){ var suite = Suite.create(suites[0], title); suites.unshift(suite); fn.call(suite); suites.shift(); return suite; }; /** * Pending describe. */ context.xdescribe = context.xcontext = context.describe.skip = function(title, fn){ var suite = Suite.create(suites[0], title); suite.pending = true; suites.unshift(suite); fn.call(suite); suites.shift(); }; /** * Exclusive suite. */ context.describe.only = function(title, fn){ var suite = context.describe(title, fn); mocha.grep(suite.fullTitle()); }; /** * Describe a specification or test-case * with the given `title` and callback `fn` * acting as a thunk. */ context.it = context.specify = function(title, fn){ var suite = suites[0]; if (suite.pending) var fn = null; var test = new Test(title, fn); suite.addTest(test); return test; }; /** * Exclusive test-case. */ context.it.only = function(title, fn){ var test = context.it(title, fn); mocha.grep(test.fullTitle()); }; /** * Pending test case. */ context.xit = context.xspecify = context.it.skip = function(title){ context.it(title); }; }); }; }); // module: interfaces/bdd.js require.register("interfaces/exports.js", function(module, exports, require){ /** * Module dependencies. */ var Suite = require('../suite') , Test = require('../test'); /** * TDD-style interface: * * exports.Array = { * '#indexOf()': { * 'should return -1 when the value is not present': function(){ * * }, * * 'should return the correct index when the value is present': function(){ * * } * } * }; * */ module.exports = function(suite){ var suites = [suite]; suite.on('require', visit); function visit(obj) { var suite; for (var key in obj) { if ('function' == typeof obj[key]) { var fn = obj[key]; switch (key) { case 'before': suites[0].beforeAll(fn); break; case 'after': suites[0].afterAll(fn); break; case 'beforeEach': suites[0].beforeEach(fn); break; case 'afterEach': suites[0].afterEach(fn); break; default: suites[0].addTest(new Test(key, fn)); } } else { var suite = Suite.create(suites[0], key); suites.unshift(suite); visit(obj[key]); suites.shift(); } } } }; }); // module: interfaces/exports.js require.register("interfaces/index.js", function(module, exports, require){ exports.bdd = require('./bdd'); exports.tdd = require('./tdd'); exports.qunit = require('./qunit'); exports.exports = require('./exports'); }); // module: interfaces/index.js require.register("interfaces/qunit.js", function(module, exports, require){ /** * Module dependencies. */ var Suite = require('../suite') , Test = require('../test'); /** * QUnit-style interface: * * suite('Array'); * * test('#length', function(){ * var arr = [1,2,3]; * ok(arr.length == 3); * }); * * test('#indexOf()', function(){ * var arr = [1,2,3]; * ok(arr.indexOf(1) == 0); * ok(arr.indexOf(2) == 1); * ok(arr.indexOf(3) == 2); * }); * * suite('String'); * * test('#length', function(){ * ok('foo'.length == 3); * }); * */ module.exports = function(suite){ var suites = [suite]; suite.on('pre-require', function(context){ /** * Execute before running tests. */ context.before = function(fn){ suites[0].beforeAll(fn); }; /** * Execute after running tests. */ context.after = function(fn){ suites[0].afterAll(fn); }; /** * Execute before each test case. */ context.beforeEach = function(fn){ suites[0].beforeEach(fn); }; /** * Execute after each test case. */ context.afterEach = function(fn){ suites[0].afterEach(fn); }; /** * Describe a "suite" with the given `title`. */ context.suite = function(title){ if (suites.length > 1) suites.shift(); var suite = Suite.create(suites[0], title); suites.unshift(suite); }; /** * Describe a specification or test-case * with the given `title` and callback `fn` * acting as a thunk. */ context.test = function(title, fn){ suites[0].addTest(new Test(title, fn)); }; }); }; }); // module: interfaces/qunit.js require.register("interfaces/tdd.js", function(module, exports, require){ /** * Module dependencies. */ var Suite = require('../suite') , Test = require('../test'); /** * TDD-style interface: * * suite('Array', function(){ * suite('#indexOf()', function(){ * suiteSetup(function(){ * * }); * * test('should return -1 when not present', function(){ * * }); * * test('should return the index when present', function(){ * * }); * * suiteTeardown(function(){ * * }); * }); * }); * */ module.exports = function(suite){ var suites = [suite]; suite.on('pre-require', function(context, file, mocha){ /** * Execute before each test case. */ context.setup = function(fn){ suites[0].beforeEach(fn); }; /** * Execute after each test case. */ context.teardown = function(fn){ suites[0].afterEach(fn); }; /** * Execute before the suite. */ context.suiteSetup = function(fn){ suites[0].beforeAll(fn); }; /** * Execute after the suite. */ context.suiteTeardown = function(fn){ suites[0].afterAll(fn); }; /** * Describe a "suite" with the given `title` * and callback `fn` containing nested suites * and/or tests. */ context.suite = function(title, fn){ var suite = Suite.create(suites[0], title); suites.unshift(suite); fn.call(suite); suites.shift(); return suite; }; /** * Exclusive test-case. */ context.suite.only = function(title, fn){ var suite = context.suite(title, fn); mocha.grep(suite.fullTitle()); }; /** * Describe a specification or test-case * with the given `title` and callback `fn` * acting as a thunk. */ context.test = function(title, fn){ var test = new Test(title, fn); suites[0].addTest(test); return test; }; /** * Exclusive test-case. */ context.test.only = function(title, fn){ var test = context.test(title, fn); mocha.grep(test.fullTitle()); }; /** * Pending test case. */ context.test.skip = function(title){ context.test(title); }; }); }; }); // module: interfaces/tdd.js require.register("mocha.js", function(module, exports, require){ /*! * mocha * Copyright(c) 2011 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ /** * Module dependencies. */ var path = require('browser/path') , utils = require('./utils'); /** * Expose `Mocha`. */ exports = module.exports = Mocha; /** * Expose internals. */ exports.utils = utils; exports.interfaces = require('./interfaces'); exports.reporters = require('./reporters'); exports.Runnable = require('./runnable'); exports.Context = require('./context'); exports.Runner = require('./runner'); exports.Suite = require('./suite'); exports.Hook = require('./hook'); exports.Test = require('./test'); /** * Return image `name` path. * * @param {String} name * @return {String} * @api private */ function image(name) { return __dirname + '/../images/' + name + '.png'; } /** * Setup mocha with `options`. * * Options: * * - `ui` name "bdd", "tdd", "exports" etc * - `reporter` reporter instance, defaults to `mocha.reporters.Dot` * - `globals` array of accepted globals * - `timeout` timeout in milliseconds * - `bail` bail on the first test failure * - `slow` milliseconds to wait before considering a test slow * - `ignoreLeaks` ignore global leaks * - `grep` string or regexp to filter tests with * * @param {Object} options * @api public */ function Mocha(options) { options = options || {}; this.files = []; this.options = options; this.grep(options.grep); this.suite = new exports.Suite('', new exports.Context); this.ui(options.ui); this.bail(options.bail); this.reporter(options.reporter); if (options.timeout) this.timeout(options.timeout); if (options.slow) this.slow(options.slow); } /** * Enable or disable bailing on the first failure. * * @param {Boolean} [bail] * @api public */ Mocha.prototype.bail = function(bail){ if (0 == arguments.length) bail = true; this.suite.bail(bail); return this; }; /** * Add test `file`. * * @param {String} file * @api public */ Mocha.prototype.addFile = function(file){ this.files.push(file); return this; }; /** * Set reporter to `reporter`, defaults to "dot". * * @param {String|Function} reporter name or constructor * @api public */ Mocha.prototype.reporter = function(reporter){ if ('function' == typeof reporter) { this._reporter = reporter; } else { reporter = reporter || 'dot'; try { this._reporter = require('./reporters/' + reporter); } catch (err) { this._reporter = require(reporter); } if (!this._reporter) throw new Error('invalid reporter "' + reporter + '"'); } return this; }; /** * Set test UI `name`, defaults to "bdd". * * @param {String} bdd * @api public */ Mocha.prototype.ui = function(name){ name = name || 'bdd'; this._ui = exports.interfaces[name]; if (!this._ui) throw new Error('invalid interface "' + name + '"'); this._ui = this._ui(this.suite); return this; }; /** * Load registered files. * * @api private */ Mocha.prototype.loadFiles = function(fn){ var self = this; var suite = this.suite; var pending = this.files.length; this.files.forEach(function(file){ file = path.resolve(file); suite.emit('pre-require', global, file, self); suite.emit('require', require(file), file, self); suite.emit('post-require', global, file, self); --pending || (fn && fn()); }); }; /** * Enable growl support. * * @api private */ Mocha.prototype._growl = function(runner, reporter) { var notify = require('growl'); runner.on('end', function(){ var stats = reporter.stats; if (stats.failures) { var msg = stats.failures + ' of ' + runner.total + ' tests failed'; notify(msg, { name: 'mocha', title: 'Failed', image: image('error') }); } else { notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', { name: 'mocha' , title: 'Passed' , image: image('ok') }); } }); }; /** * Add regexp to grep, if `re` is a string it is escaped. * * @param {RegExp|String} re * @return {Mocha} * @api public */ Mocha.prototype.grep = function(re){ this.options.grep = 'string' == typeof re ? new RegExp(utils.escapeRegexp(re)) : re; return this; }; /** * Invert `.grep()` matches. * * @return {Mocha} * @api public */ Mocha.prototype.invert = function(){ this.options.invert = true; return this; }; /** * Ignore global leaks. * * @return {Mocha} * @api public */ Mocha.prototype.ignoreLeaks = function(){ this.options.ignoreLeaks = true; return this; }; /** * Enable global leak checking. * * @return {Mocha} * @api public */ Mocha.prototype.checkLeaks = function(){ this.options.ignoreLeaks = false; return this; }; /** * Enable growl support. * * @return {Mocha} * @api public */ Mocha.prototype.growl = function(){ this.options.growl = true; return this; }; /** * Ignore `globals` array or string. * * @param {Array|String} globals * @return {Mocha} * @api public */ Mocha.prototype.globals = function(globals){ this.options.globals = (this.options.globals || []).concat(globals); return this; }; /**
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
true
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/common/test/options-store-test.js
src/common/test/options-store-test.js
/* * Copyright Adam Pritchard 2013 * MIT License : https://adampritchard.mit-license.org/ */ "use strict"; /* jshint curly:true, noempty:true, newcap:true, eqeqeq:true, eqnull:true, es5:true, undef:true, devel:true, browser:true, node:true, evil:false, latedef:false, nonew:true, trailing:false, immed:false, smarttabs:true, expr:true */ /* global describe, expect, it, before, beforeEach, after, afterEach */ /* global _, $, markdownRender, htmlToText, marked, hljs, Utils, OptionsStore */ describe('OptionsStore', function() { it('should exist', function() { expect(OptionsStore).to.exist; }); var testKeys = ['test-option-a', 'test-option-b']; beforeEach(function(done) { OptionsStore.remove(testKeys, function() { done(); }); }); after(function(done) { OptionsStore.remove(testKeys, function() { done(); }); }); it('should call callback after getting', function(done) { OptionsStore.get(function() { done(); }); }); it('should call callback after setting', function(done) { OptionsStore.set({}, function() { done(); }); }); it('should call callback after removing', function(done) { OptionsStore.remove([], function() { done(); }); }); it('should set and get null values', function(done) { OptionsStore.get(function(options) { expect(options).to.not.have.property(testKeys[0]); var obj = {}; obj[testKeys[0]] = null; OptionsStore.set(obj, function() { OptionsStore.get(function(newOptions) { expect(newOptions).to.have.property(testKeys[0]); expect(newOptions[testKeys[0]]).to.be.null; done(); }); }); }); }); it('should set and get long values', function(done) { var longString = (new Array(10*1024)).join('x'); var obj = {}; obj[testKeys[0]] = longString; OptionsStore.set(obj, function() { OptionsStore.get(function(newOptions) { expect(newOptions).to.have.property(testKeys[0]); expect(newOptions[testKeys[0]]).to.equal(longString); done(); }); }); }); it('should set and get objects', function(done) { OptionsStore.get(function(options) { expect(options).to.not.have.property(testKeys[0]); var obj = {}; obj[testKeys[0]] = { 'aaa': 111, 'bbb': 'zzz', 'ccc': ['q', 'w', 3, 4], 'ddd': {'mmm': 'nnn'} }; OptionsStore.set(obj, function() { OptionsStore.get(function(newOptions) { expect(newOptions).to.have.property(testKeys[0]); expect(newOptions[testKeys[0]]).to.eql(obj[testKeys[0]]); done(); }); }); }); }); it('should set and get arrays', function(done) { OptionsStore.get(function(options) { expect(options).to.not.have.property(testKeys[0]); var obj = {}; obj[testKeys[0]] = [1, 2, 'a', 'b', {'aa': 11}, ['q', 6]]; OptionsStore.set(obj, function() { OptionsStore.get(function(newOptions) { expect(newOptions).to.have.property(testKeys[0]); expect(newOptions[testKeys[0]]).to.eql(obj[testKeys[0]]); expect(Array.isArray(newOptions[testKeys[0]])).to.be.true; expect(newOptions[testKeys[0]]).to.have.property('length'); done(); }); }); }); }); it('should remove entries', function(done) { OptionsStore.get(function(options) { expect(options).to.not.have.property(testKeys[0]); var obj = {}; obj[testKeys[0]] = 'hi'; OptionsStore.set(obj, function() { OptionsStore.get(function(newOptions) { expect(newOptions).to.have.property(testKeys[0]); expect(newOptions[testKeys[0]]).to.eql(obj[testKeys[0]]); OptionsStore.remove(testKeys[0], function() { OptionsStore.get(function(newOptions) { expect(options).to.not.have.property(testKeys[0]); done(); }); }); }); }); }); }); it('should set and get multiple values', function(done) { OptionsStore.get(function(options) { expect(options).to.not.have.property(testKeys[0]); var obj = {}; obj[testKeys[0]] = 'value the first'; obj[testKeys[1]] = ['value the second']; OptionsStore.set(obj, function() { OptionsStore.get(function(newOptions) { expect(newOptions).to.have.property(testKeys[0]); expect(newOptions[testKeys[0]]).to.eql(obj[testKeys[0]]); expect(newOptions).to.have.property(testKeys[1]); expect(newOptions[testKeys[1]]).to.eql(obj[testKeys[1]]); done(); }); }); }); }); describe('default value behaviour', function() { beforeEach(function() { delete OptionsStore.defaults[testKeys[0]]; }); after(function() { delete OptionsStore.defaults[testKeys[0]]; }); it('should not fill in defaults if there is not a default', function(done) { OptionsStore.get(function(options) { expect(options).to.not.have.property(testKeys[0]); done(); }); }); it('should fill in defaults', function(done) { OptionsStore.get(function(options) { expect(options).to.not.have.property(testKeys[0]); // Set the default value (still pretty hacky) OptionsStore.defaults[testKeys[0]] = 'my default value'; // Make sure we get the default value now OptionsStore.get(function(options) { expect(options).to.have.property(testKeys[0]); expect(options[testKeys[0]]).to.eql('my default value'); done(); }); }); }); it('should not fill in default if value is set', function(done) { OptionsStore.get(function(options) { expect(options).to.not.have.property(testKeys[0]); // Set the default value (still pretty hacky) OptionsStore.defaults[testKeys[0]] = 'my default value'; var obj = {}; obj[testKeys[0]] = 'my non-default value'; // But also set the value in the options OptionsStore.set(obj, function() { // Make sure we do *not* get the default value now OptionsStore.get(function(options) { expect(options).to.have.property(testKeys[0]); expect(options[testKeys[0]]).to.eql('my non-default value'); done(); }); }); }); }); it('should fill in default values from files', function(done) { OptionsStore.get(function(options) { expect(options).to.not.have.property(testKeys[0]); // Set a default value that requires a XHR OptionsStore.defaults[testKeys[0]] = {'__defaultFromFile__': window.location.href}; fetch(window.location.href) .then(response => response.text()) .then(responseText => { OptionsStore.get(function(options) { expect(options).to.have.property(testKeys[0]); expect(options[testKeys[0]]).to.eql(responseText); done(); }); }); }); }); it('should upgrade defunct values to new default', function(done) { // Set our old math-value default, which we're replacing let obj = {'math-value': '<img src="https://chart.googleapis.com/chart?cht=tx&chl={urlmathcode}" alt="{mathcode}">'}; OptionsStore.set(obj, function() { // Make sure we get the new default value instead of the defunct old one OptionsStore.get(function(options) { expect(options).to.have.property('math-value'); expect(options['math-value']).to.contain('codecogs'); done(); }); }); }); }); });
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
false
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/common/test/markdown-render-test.js
src/common/test/markdown-render-test.js
/* * Copyright Adam Pritchard 2013 * MIT License : https://adampritchard.mit-license.org/ */ "use strict"; /* jshint curly:true, noempty:true, newcap:true, eqeqeq:true, eqnull:true, undef:true, devel:true, browser:true, node:true, evil:false, latedef:false, nonew:true, trailing:false, immed:false, smarttabs:true, expr:true */ /* global describe, expect, it, before, beforeEach, after, afterEach */ /* global _, MarkdownRender, htmlToText, marked, hljs, Utils, MdhHtmlToText */ describe('Markdown-Render', function() { it('should exist', function() { expect(MarkdownRender).to.exist; expect(MarkdownRender.markdownRender).to.exist; }); describe('markdownRender', function() { var userprefs = {}; beforeEach(function() { userprefs = { 'math-value': null, 'math-enabled': false, 'header-anchors-enabled': false, 'gfm-line-breaks-enabled': true }; }); it('should be okay with an empty string', function() { expect(MarkdownRender.markdownRender('', userprefs, marked, hljs)).to.equal(''); }); // Test the fix for https://github.com/adam-p/markdown-here/issues/51 it('should correctly handle links with URL text', function() { var s = '[http://example1.com](http://example2.com)'; var target = '<a href="http://example2.com">http://example1.com</a>'; expect(MarkdownRender.markdownRender(s, userprefs, marked, hljs)).to.contain(target); }); // Test the fix for https://github.com/adam-p/markdown-here/issues/51 it('should quite correctly handle pre-formatted links with URL text', function() { var s = '<a href="http://example1.com">http://example2.com</a>'; var target = '<a href="http://example1.com">http://example2.com</a>'; expect(MarkdownRender.markdownRender(s, userprefs, marked, hljs)).to.contain(target); }); it('should retain pre-formatted links', function() { var s = '<a href="http://example1.com">aaa</a>'; expect(MarkdownRender.markdownRender(s, userprefs, marked, hljs)).to.contain(s); }); // Test issue #57: https://github.com/adam-p/markdown-here/issues/57 it('should add the schema to links missing it', function() { var md = 'asdf [aaa](bbb) asdf [ccc](ftp://ddd) asdf'; var target = '<p>asdf <a href="https://bbb">aaa</a> asdf <a href="ftp://ddd">ccc</a> asdf</p>\n'; expect(MarkdownRender.markdownRender(md, userprefs, marked, hljs)).to.equal(target); }); it('should *not* add the schema to anchor links', function() { var md = 'asdf [aaa](#bbb) asdf [ccc](ftp://ddd) asdf'; var target = '<p>asdf <a href="#bbb">aaa</a> asdf <a href="ftp://ddd">ccc</a> asdf</p>\n'; expect(MarkdownRender.markdownRender(md, userprefs, marked, hljs)).to.equal(target); }); // Test issue #87: https://github.com/adam-p/markdown-here/issues/87 it('should smartypants apostrophes properly', function() { var md = "Adam's parents' place"; var target = '<p>Adam\u2019s parents\u2019 place</p>\n'; expect(MarkdownRender.markdownRender(md, userprefs, marked, hljs)).to.equal(target); }); // Test issue #83: https://github.com/adam-p/markdown-here/issues/83 it('should not alter MD-link-looking text in code blocks', function() { var md = '`[a](b)`'; var target = '<p><code>[a](b)</code></p>\n'; expect(MarkdownRender.markdownRender(md, userprefs, marked, hljs)).to.equal(target); md = '```\n[a](b)\n```'; target = '<pre><code>[a](b)\n</code></pre>'; expect(MarkdownRender.markdownRender(md, userprefs, marked, hljs)).to.equal(target); }); // Test issue #84: Math: single-character formula won't render // https://github.com/adam-p/markdown-here/issues/84 it('should render single-character math formulae', function() { userprefs = { 'math-value': '<img class="mdh-math" src="https://latex.codecogs.com/png.image?\\dpi{120}\\inline&space;{urlmathcode}" alt="{mathcode}">', 'math-enabled': true }; var md = '$x$'; var target = '<p><img class="mdh-math" src="https://latex.codecogs.com/png.image?\\dpi{120}\\inline&space;x" alt="x"></p>\n'; expect(MarkdownRender.markdownRender(md, userprefs, marked, hljs)).to.equal(target); // Make sure we haven't broken multi-character forumlae md = '$xx$'; target = '<p><img class="mdh-math" src="https://latex.codecogs.com/png.image?\\dpi{120}\\inline&space;xx" alt="xx"></p>\n'; expect(MarkdownRender.markdownRender(md, userprefs, marked, hljs)).to.equal(target); }); it('should not add anchors to headers if option is disabled', function() { userprefs['header-anchors-enabled'] = false; var md = '# Header Number 1\n\n###### Header Number 6'; var target = '<h1 id="header-number-1">Header Number 1</h1>\n<h6 id="header-number-6">Header Number 6</h6>\n'; expect(MarkdownRender.markdownRender(md, userprefs, marked, hljs)).to.equal(target); }); // Test issue #93: Add support for anchor links: https://github.com/adam-p/markdown-here/issues/93 it('should add anchors to headers if enabled', function() { userprefs['header-anchors-enabled'] = true; var md = '# Header Number 1\n\n###### Header Number 6'; var target = '<h1><a href="#" name="header-number-1"></a>Header Number 1</h1>\n<h6><a href="#" name="header-number-6"></a>Header Number 6</h6>\n'; expect(MarkdownRender.markdownRender(md, userprefs, marked, hljs)).to.equal(target); }); // Test issue #93: Add support for anchor links: https://github.com/adam-p/markdown-here/issues/93 it('should convert anchor links to point to header auto-anchors', function() { userprefs['header-anchors-enabled'] = true; var md = '[H1](#Header Number 1)\n[H6](#Header Number 6)'; var target = '<p><a href="#header-number-1">H1</a><br><a href="#header-number-6">H6</a></p>\n'; expect(MarkdownRender.markdownRender(md, userprefs, marked, hljs)).to.equal(target); }); // Test issue #93: Add support for anchor links: https://github.com/adam-p/markdown-here/issues/93 it('should handle non-alphanumeric characters in headers', function() { userprefs['header-anchors-enabled'] = true; var md = '[H1](#a&b!c*d_f)\n# a&b!c*d_f'; var target = '<p><a href="#a-amp-b-c-d_f">H1</a></p>\n<h1><a href="#" name="a-amp-b-c-d_f"></a>a&amp;b!c*d_f</h1>\n'; expect(MarkdownRender.markdownRender(md, userprefs, marked, hljs)).to.equal(target); }); // Test issue #112: Syntax Highlighting crashing rendering on bad language name: https://github.com/adam-p/markdown-here/issues/112 it('should properly render code with good language names', function() { var md = '```sql\nSELECT * FROM table WHERE id = 1\n```'; var target = '<pre><code class="hljs language-sql"><span class="hljs-keyword">SELECT</span> <span class="hljs-operator">*</span> <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">table</span> <span class="hljs-keyword">WHERE</span> id <span class="hljs-operator">=</span> <span class="hljs-number">1</span>\n</code></pre>\n'; expect(MarkdownRender.markdownRender(md, userprefs, marked, hljs)).to.equal(target); }); // Test issue #112: Syntax Highlighting crashing rendering on bad language name: https://github.com/adam-p/markdown-here/issues/112 it('should properly render code with good language names that are in the wrong (upper)case', function() { var md = '```SQL\nSELECT * FROM table WHERE id = 1\n```'; var target = '<pre><code class="hljs language-SQL"><span class="hljs-keyword">SELECT</span> <span class="hljs-operator">*</span> <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">table</span> <span class="hljs-keyword">WHERE</span> id <span class="hljs-operator">=</span> <span class="hljs-number">1</span>\n</code></pre>\n'; expect(MarkdownRender.markdownRender(md, userprefs, marked, hljs)).to.equal(target); }); // Test issue #112: Syntax Highlighting crashing rendering on bad language name: https://github.com/adam-p/markdown-here/issues/112 it('should properly render code with unsupported language names', function() { var md = '```badlang\nSELECT * FROM table WHERE id = 1\n```'; var target = '<pre><code class="hljs language-badlang">SELECT * FROM table WHERE id = 1\n</code></pre>\n'; expect(MarkdownRender.markdownRender(md, userprefs, marked, hljs)).to.equal(target); }); // Test issue #132: https://github.com/adam-p/markdown-here/issues/132 // Smart arrow it('should render smart arrows', function() { var md = '--> <-- <--> ==> <== <==>'; var target = '<p>→ ← ↔ ⇒ ⇐ ⇔</p>\n'; expect(MarkdownRender.markdownRender(md, userprefs, marked, hljs)).to.equal(target); // And should not break headers or m-dashes md = 'Arrows\n==\nAnd friends\n--\n--> <-- <--> ==> <== <==> -- m-dash'; target = '<h1 id="arrows">Arrows</h1>\n<h2 id="and-friends">And friends</h2>\n<p>→ ← ↔ ⇒ ⇐ ⇔ — m-dash</p>\n'; expect(MarkdownRender.markdownRender(md, userprefs, marked, hljs)).to.equal(target); }); // Test issue #103: option to disable GFM line breaks it('should use GFM line breaks when enabled', function() { userprefs['gfm-line-breaks-enabled'] = true; var md = 'aaa\nbbb\nccc'; var target = '<p>aaa<br>bbb<br>ccc</p>\n'; expect(MarkdownRender.markdownRender(md, userprefs, marked, hljs)).to.equal(target); }); // Test issue #103: option to disable GFM line breaks it('should not use GFM line breaks when disabled', function() { userprefs['gfm-line-breaks-enabled'] = false; var md = 'aaa\nbbb\nccc'; var target = '<p>aaa\nbbb\nccc</p>\n'; expect(MarkdownRender.markdownRender(md, userprefs, marked, hljs)).to.equal(target); }); }); // This includes going from original HTML to MD to HTML and then postprocessing. describe('HTML to Markdown to HTML', function() { var userprefs = {}; beforeEach(function() { userprefs = { 'math-value': null, 'math-enabled': false }; }); const fullRender = function(mdHTML) { const elem = document.createElement('div'); Utils.saferSetInnerHTML(elem, mdHTML); document.body.appendChild(elem); const mdhHtmlToText = new MdhHtmlToText.MdhHtmlToText(elem); let renderedMarkdown = MarkdownRender.markdownRender( mdhHtmlToText.get(), userprefs, marked, hljs); renderedMarkdown = mdhHtmlToText.postprocess(renderedMarkdown); elem.parentNode.removeChild(elem); return renderedMarkdown; }; it('should be okay with an empty string', function() { expect(fullRender('')).to.equal(''); }); // Check fix for https://github.com/adam-p/markdown-here/issues/51, which it('should correctly handle links with URL text', function() { var s = '[http://example1.com](http://example2.com)'; var target = '<a href="http://example2.com">http://example1.com</a>'; expect(fullRender(s)).to.contain(target); }); it('should quite correctly handle pre-formatted links with URL text', function() { var s = '<a href="http://example2.com">http://example1.com</a>'; var target = '<a href="http://example2.com">http://example1.com</a>'; expect(fullRender(s)).to.contain(target); }); it('should retain pre-formatted links', function() { var s = '<a href="http://example1.com">aaa</a>'; expect(fullRender(s)).to.contain(s); }); // Test that issue #69 hasn't come back: https://github.com/adam-p/markdown-here/issues/69 it('should properly render MD links that contain pre-formatted HTML links', function() { var tests = [], i; // NOTE: The expected results are affected by other content massaging, // such as adding missing links schemas. // Begin tests where the link should be converted tests.push(['asdf <a href="http://www.aaa.com">bbb</a> asdf', '<p>asdf <a href="http://www.aaa.com">bbb</a> asdf</p>\n']); tests.push(['<a href="aaa">bbb</a>', '<p><a href="https://aaa">bbb</a></p>\n']); tests.push(['[xxx](yyy) <a href="aaa">bbb</a>', '<p><a href="https://yyy">xxx</a> <a href="https://aaa">bbb</a></p>\n']); tests.push(['asdf (<a href="aaa">bbb</a>)', '<p>asdf (<a href="https://aaa">bbb</a>)</p>\n']); // Begin tests where the link should *not* be converted. // Note that some tests are affected by issue #57: MD links should automatically add scheme tests.push(['asdf [yyy](<a href="http://www.aaa.com">bbb</a>) asdf', '<p>asdf <a href="https://bbb">yyy</a> asdf</p>\n']); tests.push(['asdf [<a href="http://www.aaa.com">bbb</a>](ccc) asdf', '<p>asdf <a href="https://ccc">bbb</a> asdf</p>\n']); tests.push(['[yyy](<a href="http://www.aaa.com">bbb</a>)', '<p><a href="https://bbb">yyy</a></p>\n']); tests.push(['[yyy]( <a href="http://www.aaa.com">bbb</a>)', '<p><a href="https://bbb">yyy</a></p>\n']); tests.push(['asdf [qwer <a href="http://www.aaa.com">bbb</a>](ccc) asdf', '<p>asdf <a href="https://ccc">qwer bbb</a> asdf</p>\n']); // Begin mixed tests tests.push(['asdf [aaa](bbb) asdf <a href="http://www.aaa.com">bbb</a> asdf [yyy](<a href="http://www.aaa.com">bbb</a>) asdf', '<p>asdf <a href="https://bbb">aaa</a> asdf <a href="http://www.aaa.com">bbb</a> asdf <a href="https://bbb">yyy</a> asdf</p>\n']); // Begin tests that don't work quite right tests.push(['asdf [<a href="http://www.aaa.com">bbb</a>] asdf', '<p>asdf [bbb] asdf</p>\n']); tests.push(['asdf ](<a href="http://www.aaa.com">bbb</a>) asdf', '<p>asdf ](bbb) asdf</p>\n']); for (i = 0; i < tests.length; i++) { expect(fullRender(tests[i][0])).to.equal(tests[i][1]); } }); // Test issue #57: https://github.com/adam-p/markdown-here/issues/57 it('should add the schema to links missing it', function() { var md = 'asdf [aaa](bbb) asdf [ccc](ftp://ddd) asdf'; var target = '<p>asdf <a href="https://bbb">aaa</a> asdf <a href="ftp://ddd">ccc</a> asdf</p>\n'; expect(fullRender(md)).to.equal(target); }); it('should *not* add the schema to anchor links', function() { var md = 'asdf [aaa](#bbb) asdf [ccc](ftp://ddd) asdf'; var target = '<p>asdf <a href="#bbb">aaa</a> asdf <a href="ftp://ddd">ccc</a> asdf</p>\n'; expect(fullRender(md)).to.equal(target); }); // Test issue #87: https://github.com/adam-p/markdown-here/issues/87 it('should smartypants apostrophes properly', function() { var md = "Adam's parents' place"; var target = '<p>Adam\u2019s parents\u2019 place</p>\n'; expect(fullRender(md)).to.equal(target); }); // Test issue #83: https://github.com/adam-p/markdown-here/issues/83 it('should not alter MD-link-looking text in code blocks', function() { var md = '`[a](b)`'; var target = '<p><code>[a](b)</code></p>\n'; expect(fullRender(md)).to.equal(target); md = '```<br>[a](b)<br>```'; target = '<pre><code>[a](b)\n</code></pre>'; expect(fullRender(md)).to.equal(target); }); // Test issue #84: Math: single-character formula won't render // https://github.com/adam-p/markdown-here/issues/84 it('should render single-character math formulae', function() { userprefs = { 'math-value': '<img class="mdh-math" src="https://latex.codecogs.com/png.image?\\dpi{120}\\inline&space;{urlmathcode}" alt="{mathcode}">', 'math-enabled': true }; var md = '$x$'; var target = '<p><img class="mdh-math" src="https://latex.codecogs.com/png.image?\\dpi{120}\\inline&space;x" alt="x"></p>\n'; expect(fullRender(md)).to.equal(target); // Make sure we haven't broken multi-character forumlae md = '$xx$'; target = '<p><img class="mdh-math" src="https://latex.codecogs.com/png.image?\\dpi{120}\\inline&space;xx" alt="xx"></p>\n'; expect(fullRender(md)).to.equal(target); }); }); });
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
false
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/src/common/highlightjs/highlight.js
src/common/highlightjs/highlight.js
/*! Highlight.js v11.11.1 (git: 08cb242e7d) (c) 2006-2025 Josh Goebel <hello@joshgoebel.com> and other contributors License: BSD-3-Clause */ var hljs = (function () { 'use strict'; /* eslint-disable no-multi-assign */ function deepFreeze(obj) { if (obj instanceof Map) { obj.clear = obj.delete = obj.set = function () { throw new Error('map is read-only'); }; } else if (obj instanceof Set) { obj.add = obj.clear = obj.delete = function () { throw new Error('set is read-only'); }; } // Freeze self Object.freeze(obj); Object.getOwnPropertyNames(obj).forEach((name) => { const prop = obj[name]; const type = typeof prop; // Freeze prop if it is an object or function and also not already frozen if ((type === 'object' || type === 'function') && !Object.isFrozen(prop)) { deepFreeze(prop); } }); return obj; } /** @typedef {import('highlight.js').CallbackResponse} CallbackResponse */ /** @typedef {import('highlight.js').CompiledMode} CompiledMode */ /** @implements CallbackResponse */ class Response { /** * @param {CompiledMode} mode */ constructor(mode) { // eslint-disable-next-line no-undefined if (mode.data === undefined) mode.data = {}; this.data = mode.data; this.isMatchIgnored = false; } ignoreMatch() { this.isMatchIgnored = true; } } /** * @param {string} value * @returns {string} */ function escapeHTML(value) { return value .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#x27;'); } /** * performs a shallow merge of multiple objects into one * * @template T * @param {T} original * @param {Record<string,any>[]} objects * @returns {T} a single new object */ function inherit$1(original, ...objects) { /** @type Record<string,any> */ const result = Object.create(null); for (const key in original) { result[key] = original[key]; } objects.forEach(function(obj) { for (const key in obj) { result[key] = obj[key]; } }); return /** @type {T} */ (result); } /** * @typedef {object} Renderer * @property {(text: string) => void} addText * @property {(node: Node) => void} openNode * @property {(node: Node) => void} closeNode * @property {() => string} value */ /** @typedef {{scope?: string, language?: string, sublanguage?: boolean}} Node */ /** @typedef {{walk: (r: Renderer) => void}} Tree */ /** */ const SPAN_CLOSE = '</span>'; /** * Determines if a node needs to be wrapped in <span> * * @param {Node} node */ const emitsWrappingTags = (node) => { // rarely we can have a sublanguage where language is undefined // TODO: track down why return !!node.scope; }; /** * * @param {string} name * @param {{prefix:string}} options */ const scopeToCSSClass = (name, { prefix }) => { // sub-language if (name.startsWith("language:")) { return name.replace("language:", "language-"); } // tiered scope: comment.line if (name.includes(".")) { const pieces = name.split("."); return [ `${prefix}${pieces.shift()}`, ...(pieces.map((x, i) => `${x}${"_".repeat(i + 1)}`)) ].join(" "); } // simple scope return `${prefix}${name}`; }; /** @type {Renderer} */ class HTMLRenderer { /** * Creates a new HTMLRenderer * * @param {Tree} parseTree - the parse tree (must support `walk` API) * @param {{classPrefix: string}} options */ constructor(parseTree, options) { this.buffer = ""; this.classPrefix = options.classPrefix; parseTree.walk(this); } /** * Adds texts to the output stream * * @param {string} text */ addText(text) { this.buffer += escapeHTML(text); } /** * Adds a node open to the output stream (if needed) * * @param {Node} node */ openNode(node) { if (!emitsWrappingTags(node)) return; const className = scopeToCSSClass(node.scope, { prefix: this.classPrefix }); this.span(className); } /** * Adds a node close to the output stream (if needed) * * @param {Node} node */ closeNode(node) { if (!emitsWrappingTags(node)) return; this.buffer += SPAN_CLOSE; } /** * returns the accumulated buffer */ value() { return this.buffer; } // helpers /** * Builds a span element * * @param {string} className */ span(className) { this.buffer += `<span class="${className}">`; } } /** @typedef {{scope?: string, language?: string, children: Node[]} | string} Node */ /** @typedef {{scope?: string, language?: string, children: Node[]} } DataNode */ /** @typedef {import('highlight.js').Emitter} Emitter */ /** */ /** @returns {DataNode} */ const newNode = (opts = {}) => { /** @type DataNode */ const result = { children: [] }; Object.assign(result, opts); return result; }; class TokenTree { constructor() { /** @type DataNode */ this.rootNode = newNode(); this.stack = [this.rootNode]; } get top() { return this.stack[this.stack.length - 1]; } get root() { return this.rootNode; } /** @param {Node} node */ add(node) { this.top.children.push(node); } /** @param {string} scope */ openNode(scope) { /** @type Node */ const node = newNode({ scope }); this.add(node); this.stack.push(node); } closeNode() { if (this.stack.length > 1) { return this.stack.pop(); } // eslint-disable-next-line no-undefined return undefined; } closeAllNodes() { while (this.closeNode()); } toJSON() { return JSON.stringify(this.rootNode, null, 4); } /** * @typedef { import("./html_renderer").Renderer } Renderer * @param {Renderer} builder */ walk(builder) { // this does not return this.constructor._walk(builder, this.rootNode); // this works // return TokenTree._walk(builder, this.rootNode); } /** * @param {Renderer} builder * @param {Node} node */ static _walk(builder, node) { if (typeof node === "string") { builder.addText(node); } else if (node.children) { builder.openNode(node); node.children.forEach((child) => this._walk(builder, child)); builder.closeNode(node); } return builder; } /** * @param {Node} node */ static _collapse(node) { if (typeof node === "string") return; if (!node.children) return; if (node.children.every(el => typeof el === "string")) { // node.text = node.children.join(""); // delete node.children; node.children = [node.children.join("")]; } else { node.children.forEach((child) => { TokenTree._collapse(child); }); } } } /** Currently this is all private API, but this is the minimal API necessary that an Emitter must implement to fully support the parser. Minimal interface: - addText(text) - __addSublanguage(emitter, subLanguageName) - startScope(scope) - endScope() - finalize() - toHTML() */ /** * @implements {Emitter} */ class TokenTreeEmitter extends TokenTree { /** * @param {*} options */ constructor(options) { super(); this.options = options; } /** * @param {string} text */ addText(text) { if (text === "") { return; } this.add(text); } /** @param {string} scope */ startScope(scope) { this.openNode(scope); } endScope() { this.closeNode(); } /** * @param {Emitter & {root: DataNode}} emitter * @param {string} name */ __addSublanguage(emitter, name) { /** @type DataNode */ const node = emitter.root; if (name) node.scope = `language:${name}`; this.add(node); } toHTML() { const renderer = new HTMLRenderer(this, this.options); return renderer.value(); } finalize() { this.closeAllNodes(); return true; } } /** * @param {string} value * @returns {RegExp} * */ /** * @param {RegExp | string } re * @returns {string} */ function source(re) { if (!re) return null; if (typeof re === "string") return re; return re.source; } /** * @param {RegExp | string } re * @returns {string} */ function lookahead(re) { return concat('(?=', re, ')'); } /** * @param {RegExp | string } re * @returns {string} */ function anyNumberOfTimes(re) { return concat('(?:', re, ')*'); } /** * @param {RegExp | string } re * @returns {string} */ function optional(re) { return concat('(?:', re, ')?'); } /** * @param {...(RegExp | string) } args * @returns {string} */ function concat(...args) { const joined = args.map((x) => source(x)).join(""); return joined; } /** * @param { Array<string | RegExp | Object> } args * @returns {object} */ function stripOptionsFromArgs(args) { const opts = args[args.length - 1]; if (typeof opts === 'object' && opts.constructor === Object) { args.splice(args.length - 1, 1); return opts; } else { return {}; } } /** @typedef { {capture?: boolean} } RegexEitherOptions */ /** * Any of the passed expresssions may match * * Creates a huge this | this | that | that match * @param {(RegExp | string)[] | [...(RegExp | string)[], RegexEitherOptions]} args * @returns {string} */ function either(...args) { /** @type { object & {capture?: boolean} } */ const opts = stripOptionsFromArgs(args); const joined = '(' + (opts.capture ? "" : "?:") + args.map((x) => source(x)).join("|") + ")"; return joined; } /** * @param {RegExp | string} re * @returns {number} */ function countMatchGroups(re) { return (new RegExp(re.toString() + '|')).exec('').length - 1; } /** * Does lexeme start with a regular expression match at the beginning * @param {RegExp} re * @param {string} lexeme */ function startsWith(re, lexeme) { const match = re && re.exec(lexeme); return match && match.index === 0; } // BACKREF_RE matches an open parenthesis or backreference. To avoid // an incorrect parse, it additionally matches the following: // - [...] elements, where the meaning of parentheses and escapes change // - other escape sequences, so we do not misparse escape sequences as // interesting elements // - non-matching or lookahead parentheses, which do not capture. These // follow the '(' with a '?'. const BACKREF_RE = /\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./; // **INTERNAL** Not intended for outside usage // join logically computes regexps.join(separator), but fixes the // backreferences so they continue to match. // it also places each individual regular expression into it's own // match group, keeping track of the sequencing of those match groups // is currently an exercise for the caller. :-) /** * @param {(string | RegExp)[]} regexps * @param {{joinWith: string}} opts * @returns {string} */ function _rewriteBackreferences(regexps, { joinWith }) { let numCaptures = 0; return regexps.map((regex) => { numCaptures += 1; const offset = numCaptures; let re = source(regex); let out = ''; while (re.length > 0) { const match = BACKREF_RE.exec(re); if (!match) { out += re; break; } out += re.substring(0, match.index); re = re.substring(match.index + match[0].length); if (match[0][0] === '\\' && match[1]) { // Adjust the backreference. out += '\\' + String(Number(match[1]) + offset); } else { out += match[0]; if (match[0] === '(') { numCaptures++; } } } return out; }).map(re => `(${re})`).join(joinWith); } /** @typedef {import('highlight.js').Mode} Mode */ /** @typedef {import('highlight.js').ModeCallback} ModeCallback */ // Common regexps const MATCH_NOTHING_RE = /\b\B/; const IDENT_RE = '[a-zA-Z]\\w*'; const UNDERSCORE_IDENT_RE = '[a-zA-Z_]\\w*'; const NUMBER_RE = '\\b\\d+(\\.\\d+)?'; const C_NUMBER_RE = '(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)'; // 0x..., 0..., decimal, float const BINARY_NUMBER_RE = '\\b(0b[01]+)'; // 0b... const RE_STARTERS_RE = '!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~'; /** * @param { Partial<Mode> & {binary?: string | RegExp} } opts */ const SHEBANG = (opts = {}) => { const beginShebang = /^#![ ]*\//; if (opts.binary) { opts.begin = concat( beginShebang, /.*\b/, opts.binary, /\b.*/); } return inherit$1({ scope: 'meta', begin: beginShebang, end: /$/, relevance: 0, /** @type {ModeCallback} */ "on:begin": (m, resp) => { if (m.index !== 0) resp.ignoreMatch(); } }, opts); }; // Common modes const BACKSLASH_ESCAPE = { begin: '\\\\[\\s\\S]', relevance: 0 }; const APOS_STRING_MODE = { scope: 'string', begin: '\'', end: '\'', illegal: '\\n', contains: [BACKSLASH_ESCAPE] }; const QUOTE_STRING_MODE = { scope: 'string', begin: '"', end: '"', illegal: '\\n', contains: [BACKSLASH_ESCAPE] }; const PHRASAL_WORDS_MODE = { begin: /\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/ }; /** * Creates a comment mode * * @param {string | RegExp} begin * @param {string | RegExp} end * @param {Mode | {}} [modeOptions] * @returns {Partial<Mode>} */ const COMMENT = function(begin, end, modeOptions = {}) { const mode = inherit$1( { scope: 'comment', begin, end, contains: [] }, modeOptions ); mode.contains.push({ scope: 'doctag', // hack to avoid the space from being included. the space is necessary to // match here to prevent the plain text rule below from gobbling up doctags begin: '[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)', end: /(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/, excludeBegin: true, relevance: 0 }); const ENGLISH_WORD = either( // list of common 1 and 2 letter words in English "I", "a", "is", "so", "us", "to", "at", "if", "in", "it", "on", // note: this is not an exhaustive list of contractions, just popular ones /[A-Za-z]+['](d|ve|re|ll|t|s|n)/, // contractions - can't we'd they're let's, etc /[A-Za-z]+[-][a-z]+/, // `no-way`, etc. /[A-Za-z][a-z]{2,}/ // allow capitalized words at beginning of sentences ); // looking like plain text, more likely to be a comment mode.contains.push( { // TODO: how to include ", (, ) without breaking grammars that use these for // comment delimiters? // begin: /[ ]+([()"]?([A-Za-z'-]{3,}|is|a|I|so|us|[tT][oO]|at|if|in|it|on)[.]?[()":]?([.][ ]|[ ]|\))){3}/ // --- // this tries to find sequences of 3 english words in a row (without any // "programming" type syntax) this gives us a strong signal that we've // TRULY found a comment - vs perhaps scanning with the wrong language. // It's possible to find something that LOOKS like the start of the // comment - but then if there is no readable text - good chance it is a // false match and not a comment. // // for a visual example please see: // https://github.com/highlightjs/highlight.js/issues/2827 begin: concat( /[ ]+/, // necessary to prevent us gobbling up doctags like /* @author Bob Mcgill */ '(', ENGLISH_WORD, /[.]?[:]?([.][ ]|[ ])/, '){3}') // look for 3 words in a row } ); return mode; }; const C_LINE_COMMENT_MODE = COMMENT('//', '$'); const C_BLOCK_COMMENT_MODE = COMMENT('/\\*', '\\*/'); const HASH_COMMENT_MODE = COMMENT('#', '$'); const NUMBER_MODE = { scope: 'number', begin: NUMBER_RE, relevance: 0 }; const C_NUMBER_MODE = { scope: 'number', begin: C_NUMBER_RE, relevance: 0 }; const BINARY_NUMBER_MODE = { scope: 'number', begin: BINARY_NUMBER_RE, relevance: 0 }; const REGEXP_MODE = { scope: "regexp", begin: /\/(?=[^/\n]*\/)/, end: /\/[gimuy]*/, contains: [ BACKSLASH_ESCAPE, { begin: /\[/, end: /\]/, relevance: 0, contains: [BACKSLASH_ESCAPE] } ] }; const TITLE_MODE = { scope: 'title', begin: IDENT_RE, relevance: 0 }; const UNDERSCORE_TITLE_MODE = { scope: 'title', begin: UNDERSCORE_IDENT_RE, relevance: 0 }; const METHOD_GUARD = { // excludes method names from keyword processing begin: '\\.\\s*' + UNDERSCORE_IDENT_RE, relevance: 0 }; /** * Adds end same as begin mechanics to a mode * * Your mode must include at least a single () match group as that first match * group is what is used for comparison * @param {Partial<Mode>} mode */ const END_SAME_AS_BEGIN = function(mode) { return Object.assign(mode, { /** @type {ModeCallback} */ 'on:begin': (m, resp) => { resp.data._beginMatch = m[1]; }, /** @type {ModeCallback} */ 'on:end': (m, resp) => { if (resp.data._beginMatch !== m[1]) resp.ignoreMatch(); } }); }; var MODES = /*#__PURE__*/Object.freeze({ __proto__: null, APOS_STRING_MODE: APOS_STRING_MODE, BACKSLASH_ESCAPE: BACKSLASH_ESCAPE, BINARY_NUMBER_MODE: BINARY_NUMBER_MODE, BINARY_NUMBER_RE: BINARY_NUMBER_RE, COMMENT: COMMENT, C_BLOCK_COMMENT_MODE: C_BLOCK_COMMENT_MODE, C_LINE_COMMENT_MODE: C_LINE_COMMENT_MODE, C_NUMBER_MODE: C_NUMBER_MODE, C_NUMBER_RE: C_NUMBER_RE, END_SAME_AS_BEGIN: END_SAME_AS_BEGIN, HASH_COMMENT_MODE: HASH_COMMENT_MODE, IDENT_RE: IDENT_RE, MATCH_NOTHING_RE: MATCH_NOTHING_RE, METHOD_GUARD: METHOD_GUARD, NUMBER_MODE: NUMBER_MODE, NUMBER_RE: NUMBER_RE, PHRASAL_WORDS_MODE: PHRASAL_WORDS_MODE, QUOTE_STRING_MODE: QUOTE_STRING_MODE, REGEXP_MODE: REGEXP_MODE, RE_STARTERS_RE: RE_STARTERS_RE, SHEBANG: SHEBANG, TITLE_MODE: TITLE_MODE, UNDERSCORE_IDENT_RE: UNDERSCORE_IDENT_RE, UNDERSCORE_TITLE_MODE: UNDERSCORE_TITLE_MODE }); /** @typedef {import('highlight.js').CallbackResponse} CallbackResponse @typedef {import('highlight.js').CompilerExt} CompilerExt */ // Grammar extensions / plugins // See: https://github.com/highlightjs/highlight.js/issues/2833 // Grammar extensions allow "syntactic sugar" to be added to the grammar modes // without requiring any underlying changes to the compiler internals. // `compileMatch` being the perfect small example of now allowing a grammar // author to write `match` when they desire to match a single expression rather // than being forced to use `begin`. The extension then just moves `match` into // `begin` when it runs. Ie, no features have been added, but we've just made // the experience of writing (and reading grammars) a little bit nicer. // ------ // TODO: We need negative look-behind support to do this properly /** * Skip a match if it has a preceding dot * * This is used for `beginKeywords` to prevent matching expressions such as * `bob.keyword.do()`. The mode compiler automatically wires this up as a * special _internal_ 'on:begin' callback for modes with `beginKeywords` * @param {RegExpMatchArray} match * @param {CallbackResponse} response */ function skipIfHasPrecedingDot(match, response) { const before = match.input[match.index - 1]; if (before === ".") { response.ignoreMatch(); } } /** * * @type {CompilerExt} */ function scopeClassName(mode, _parent) { // eslint-disable-next-line no-undefined if (mode.className !== undefined) { mode.scope = mode.className; delete mode.className; } } /** * `beginKeywords` syntactic sugar * @type {CompilerExt} */ function beginKeywords(mode, parent) { if (!parent) return; if (!mode.beginKeywords) return; // for languages with keywords that include non-word characters checking for // a word boundary is not sufficient, so instead we check for a word boundary // or whitespace - this does no harm in any case since our keyword engine // doesn't allow spaces in keywords anyways and we still check for the boundary // first mode.begin = '\\b(' + mode.beginKeywords.split(' ').join('|') + ')(?!\\.)(?=\\b|\\s)'; mode.__beforeBegin = skipIfHasPrecedingDot; mode.keywords = mode.keywords || mode.beginKeywords; delete mode.beginKeywords; // prevents double relevance, the keywords themselves provide // relevance, the mode doesn't need to double it // eslint-disable-next-line no-undefined if (mode.relevance === undefined) mode.relevance = 0; } /** * Allow `illegal` to contain an array of illegal values * @type {CompilerExt} */ function compileIllegal(mode, _parent) { if (!Array.isArray(mode.illegal)) return; mode.illegal = either(...mode.illegal); } /** * `match` to match a single expression for readability * @type {CompilerExt} */ function compileMatch(mode, _parent) { if (!mode.match) return; if (mode.begin || mode.end) throw new Error("begin & end are not supported with match"); mode.begin = mode.match; delete mode.match; } /** * provides the default 1 relevance to all modes * @type {CompilerExt} */ function compileRelevance(mode, _parent) { // eslint-disable-next-line no-undefined if (mode.relevance === undefined) mode.relevance = 1; } // allow beforeMatch to act as a "qualifier" for the match // the full match begin must be [beforeMatch][begin] const beforeMatchExt = (mode, parent) => { if (!mode.beforeMatch) return; // starts conflicts with endsParent which we need to make sure the child // rule is not matched multiple times if (mode.starts) throw new Error("beforeMatch cannot be used with starts"); const originalMode = Object.assign({}, mode); Object.keys(mode).forEach((key) => { delete mode[key]; }); mode.keywords = originalMode.keywords; mode.begin = concat(originalMode.beforeMatch, lookahead(originalMode.begin)); mode.starts = { relevance: 0, contains: [ Object.assign(originalMode, { endsParent: true }) ] }; mode.relevance = 0; delete originalMode.beforeMatch; }; // keywords that should have no default relevance value const COMMON_KEYWORDS = [ 'of', 'and', 'for', 'in', 'not', 'or', 'if', 'then', 'parent', // common variable name 'list', // common variable name 'value' // common variable name ]; const DEFAULT_KEYWORD_SCOPE = "keyword"; /** * Given raw keywords from a language definition, compile them. * * @param {string | Record<string,string|string[]> | Array<string>} rawKeywords * @param {boolean} caseInsensitive */ function compileKeywords(rawKeywords, caseInsensitive, scopeName = DEFAULT_KEYWORD_SCOPE) { /** @type {import("highlight.js/private").KeywordDict} */ const compiledKeywords = Object.create(null); // input can be a string of keywords, an array of keywords, or a object with // named keys representing scopeName (which can then point to a string or array) if (typeof rawKeywords === 'string') { compileList(scopeName, rawKeywords.split(" ")); } else if (Array.isArray(rawKeywords)) { compileList(scopeName, rawKeywords); } else { Object.keys(rawKeywords).forEach(function(scopeName) { // collapse all our objects back into the parent object Object.assign( compiledKeywords, compileKeywords(rawKeywords[scopeName], caseInsensitive, scopeName) ); }); } return compiledKeywords; // --- /** * Compiles an individual list of keywords * * Ex: "for if when while|5" * * @param {string} scopeName * @param {Array<string>} keywordList */ function compileList(scopeName, keywordList) { if (caseInsensitive) { keywordList = keywordList.map(x => x.toLowerCase()); } keywordList.forEach(function(keyword) { const pair = keyword.split('|'); compiledKeywords[pair[0]] = [scopeName, scoreForKeyword(pair[0], pair[1])]; }); } } /** * Returns the proper score for a given keyword * * Also takes into account comment keywords, which will be scored 0 UNLESS * another score has been manually assigned. * @param {string} keyword * @param {string} [providedScore] */ function scoreForKeyword(keyword, providedScore) { // manual scores always win over common keywords // so you can force a score of 1 if you really insist if (providedScore) { return Number(providedScore); } return commonKeyword(keyword) ? 0 : 1; } /** * Determines if a given keyword is common or not * * @param {string} keyword */ function commonKeyword(keyword) { return COMMON_KEYWORDS.includes(keyword.toLowerCase()); } /* For the reasoning behind this please see: https://github.com/highlightjs/highlight.js/issues/2880#issuecomment-747275419 */ /** * @type {Record<string, boolean>} */ const seenDeprecations = {}; /** * @param {string} message */ const error = (message) => { console.error(message); }; /** * @param {string} message * @param {any} args */ const warn = (message, ...args) => { console.log(`WARN: ${message}`, ...args); }; /** * @param {string} version * @param {string} message */ const deprecated = (version, message) => { if (seenDeprecations[`${version}/${message}`]) return; console.log(`Deprecated as of ${version}. ${message}`); seenDeprecations[`${version}/${message}`] = true; }; /* eslint-disable no-throw-literal */ /** @typedef {import('highlight.js').CompiledMode} CompiledMode */ const MultiClassError = new Error(); /** * Renumbers labeled scope names to account for additional inner match * groups that otherwise would break everything. * * Lets say we 3 match scopes: * * { 1 => ..., 2 => ..., 3 => ... } * * So what we need is a clean match like this: * * (a)(b)(c) => [ "a", "b", "c" ] * * But this falls apart with inner match groups: * * (a)(((b)))(c) => ["a", "b", "b", "b", "c" ] * * Our scopes are now "out of alignment" and we're repeating `b` 3 times. * What needs to happen is the numbers are remapped: * * { 1 => ..., 2 => ..., 5 => ... } * * We also need to know that the ONLY groups that should be output * are 1, 2, and 5. This function handles this behavior. * * @param {CompiledMode} mode * @param {Array<RegExp | string>} regexes * @param {{key: "beginScope"|"endScope"}} opts */ function remapScopeNames(mode, regexes, { key }) { let offset = 0; const scopeNames = mode[key]; /** @type Record<number,boolean> */ const emit = {}; /** @type Record<number,string> */ const positions = {}; for (let i = 1; i <= regexes.length; i++) { positions[i + offset] = scopeNames[i]; emit[i + offset] = true; offset += countMatchGroups(regexes[i - 1]); } // we use _emit to keep track of which match groups are "top-level" to avoid double // output from inside match groups mode[key] = positions; mode[key]._emit = emit; mode[key]._multi = true; } /** * @param {CompiledMode} mode */ function beginMultiClass(mode) { if (!Array.isArray(mode.begin)) return; if (mode.skip || mode.excludeBegin || mode.returnBegin) { error("skip, excludeBegin, returnBegin not compatible with beginScope: {}"); throw MultiClassError; } if (typeof mode.beginScope !== "object" || mode.beginScope === null) { error("beginScope must be object"); throw MultiClassError; } remapScopeNames(mode, mode.begin, { key: "beginScope" }); mode.begin = _rewriteBackreferences(mode.begin, { joinWith: "" }); } /** * @param {CompiledMode} mode */ function endMultiClass(mode) { if (!Array.isArray(mode.end)) return; if (mode.skip || mode.excludeEnd || mode.returnEnd) { error("skip, excludeEnd, returnEnd not compatible with endScope: {}"); throw MultiClassError; } if (typeof mode.endScope !== "object" || mode.endScope === null) { error("endScope must be object"); throw MultiClassError; } remapScopeNames(mode, mode.end, { key: "endScope" }); mode.end = _rewriteBackreferences(mode.end, { joinWith: "" }); } /** * this exists only to allow `scope: {}` to be used beside `match:` * Otherwise `beginScope` would necessary and that would look weird { match: [ /def/, /\w+/ ] scope: { 1: "keyword" , 2: "title" } } * @param {CompiledMode} mode */ function scopeSugar(mode) { if (mode.scope && typeof mode.scope === "object" && mode.scope !== null) { mode.beginScope = mode.scope; delete mode.scope; } } /** * @param {CompiledMode} mode */ function MultiClass(mode) { scopeSugar(mode); if (typeof mode.beginScope === "string") { mode.beginScope = { _wrap: mode.beginScope }; } if (typeof mode.endScope === "string") { mode.endScope = { _wrap: mode.endScope }; } beginMultiClass(mode); endMultiClass(mode); } /** @typedef {import('highlight.js').Mode} Mode @typedef {import('highlight.js').CompiledMode} CompiledMode @typedef {import('highlight.js').Language} Language @typedef {import('highlight.js').HLJSPlugin} HLJSPlugin @typedef {import('highlight.js').CompiledLanguage} CompiledLanguage */ // compilation /** * Compiles a language definition result * * Given the raw result of a language definition (Language), compiles this so * that it is ready for highlighting code. * @param {Language} language * @returns {CompiledLanguage} */ function compileLanguage(language) { /** * Builds a regex with the case sensitivity of the current language * * @param {RegExp | string} value * @param {boolean} [global] */ function langRe(value, global) { return new RegExp( source(value), 'm' + (language.case_insensitive ? 'i' : '') + (language.unicodeRegex ? 'u' : '') + (global ? 'g' : '') ); } /** Stores multiple regular expressions and allows you to quickly search for them all in a string simultaneously - returning the first match. It does this by creating a huge (a|b|c) regex - each individual item wrapped with () and joined by `|` - using match groups to track position. When a match is found checking which position in the array has content allows us to figure out which of the original regexes / match groups triggered the match. The match object itself (the result of `Regex.exec`) is returned but also enhanced by merging in any meta-data that was registered with the regex. This is how we keep track of which mode matched, and what type of rule (`illegal`, `begin`, end, etc). */ class MultiRegex { constructor() { this.matchIndexes = {}; // @ts-ignore this.regexes = []; this.matchAt = 1; this.position = 0; } // @ts-ignore addRule(re, opts) { opts.position = this.position++; // @ts-ignore this.matchIndexes[this.matchAt] = opts; this.regexes.push([opts, re]);
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
true
adam-p/markdown-here
https://github.com/adam-p/markdown-here/blob/e00d005299922198aef968e0cd42b275525c20a6/utils/build.js
utils/build.js
/* * Copyright Adam Pritchard 2015 * MIT License : https://adampritchard.mit-license.org/ */ /* jslint node: true */ "use strict"; const fs = require('fs'); const file = require('file'); const archiver = require('archiver'); // TODO: Update Thunderbird build var BASE_DIR = '..'; var SRC_DIR = file.path.join(BASE_DIR, 'src'); var DIST_DIR = file.path.join(BASE_DIR, 'dist'); var CHROME_EXTENSION = file.path.join(DIST_DIR, 'chrome.zip'); var FIREFOX_EXTENSION = file.path.join(DIST_DIR, 'firefox.zip'); var THUNDERBIRD_EXTENSION = file.path.join(DIST_DIR, 'thunderbird.xpi'); var CHROME_INPUT = [/^manifest\.json$/, /^common(\\|\/)/, /^chrome(\\|\/)/, /^_locales(\\|\/)/]; var FIREFOX_INPUT = CHROME_INPUT; var THUNDERBIRD_INPUT = [/^chrome.manifest$/, /^install.rdf$/, /^common(\\|\/)/, /^firefox(\\|\/)/]; var CHROME_PLATFORM = 'chrome'; var FIREFOX_PLATFORM = 'firefox'; var THUNDERBIRD_PLATFORM = 'thunderbird'; var skipFileRegexes = [/^common(\\|\/)test(\\|\/)/, // OS files and temp files /\.DS_Store$/, /.+\.bts$/, /desktop\.ini$/, /Thumbs.db$/]; var javascriptFileRegex = /.+\.js$/; var manifestJsonFileRegex = /manifest\.json$/ // Checks for a match for fpath in inputArray (which should be CHROME_INPUT or FIREFOX_INPUT). // Returns null if no match, or the zippable path to the file. function fnameMatch(fpath, inputArray) { var fname = file.path.relativePath(SRC_DIR, fpath); var i; for (i = 0; i < skipFileRegexes.length; i++) { if (skipFileRegexes[i].test(fname)) { return null; } } for (i = 0; i < inputArray.length; i++) { if (inputArray[i].test(fname)) { return fname; } } return null; } // Add a file to the extension zip function addBuildFile(platformName, zip, fullPath, zipPath) { if (platformName === CHROME_PLATFORM && manifestJsonFileRegex.test(fullPath)) { // Remove the Firefox-specific stuff from manifest.json when building for Chrome. let fileContents = fs.readFileSync(fullPath, {encoding: 'utf8'}); fileContents = fileContents.replace(/,"browser_specific_settings":[^{]*{[^{]*{[^}]*}[^}]*}/m, ''); zip.append(fileContents, { name: zipPath }); } else { zip.file(fullPath, { name: zipPath }); } } // Initialize the extension zips. Returns an object like: // { chrome: chromeZip, firefox: firefoxZip, thunderbird: thunderbirdZip } function setUpZips() { file.mkdirsSync(DIST_DIR); if (fs.existsSync(CHROME_EXTENSION)) { fs.unlinkSync(CHROME_EXTENSION); } if (fs.existsSync(FIREFOX_EXTENSION)) { fs.unlinkSync(FIREFOX_EXTENSION); } if (fs.existsSync(THUNDERBIRD_EXTENSION)) { fs.unlinkSync(THUNDERBIRD_EXTENSION); } var chromeZip = new archiver('zip'); // Chrome will reject the zip if there's no compression var firefoxZip = new archiver('zip'); var thunderbirdZip = new archiver('zip'); // addons.thunderbird.net rejects the xpi if there's no compression chromeZip.on('error', function(err) { console.log('chromeZip error:', err); throw err; }); firefoxZip.on('error', function(err) { console.log('firefoxZip error:', err); throw err; }); thunderbirdZip.on('error', function(err) { console.log('thunderbirdZip error:', err); throw err; }); chromeZip.pipe(fs.createWriteStream(CHROME_EXTENSION)); firefoxZip.pipe(fs.createWriteStream(FIREFOX_EXTENSION)); thunderbirdZip.pipe(fs.createWriteStream(THUNDERBIRD_EXTENSION)); return { chrome: chromeZip, firefox: firefoxZip, thunderbird: thunderbirdZip }; } function main() { var zips = setUpZips(); file.walkSync(SRC_DIR, function(dirPath, dirs, files) { for (var i = 0; i < files.length; i++) { var fullPath = file.path.join(dirPath, files[i]); var fnameChrome = fnameMatch(fullPath, CHROME_INPUT); var fnameFirefox = fnameMatch(fullPath, FIREFOX_INPUT); var fnameThunderbird = fnameMatch(fullPath, THUNDERBIRD_INPUT); if (fnameChrome) { addBuildFile(CHROME_PLATFORM, zips.chrome, fullPath, fnameChrome); } if (fnameFirefox) { addBuildFile(FIREFOX_PLATFORM, zips.firefox, fullPath, fnameFirefox); } if (fnameThunderbird) { addBuildFile(THUNDERBIRD_PLATFORM, zips.thunderbird, fullPath, fnameThunderbird); } } }); zips.chrome.finalize(); zips.firefox.finalize(); zips.thunderbird.finalize(); console.log('Done! Built extensions written to', DIST_DIR); } main();
javascript
MIT
e00d005299922198aef968e0cd42b275525c20a6
2026-01-04T14:56:52.113793Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/tasks/screencast-start.js
tasks/screencast-start.js
#!/usr/bin/env node /** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; const execa = require('execa'); const meow = require('meow'); const multimatch = require('multimatch'); main(meow()); function main(cli) { let count = 0; const start = Date.now(); const duration = parseInt(cli.flags.timeout, 10) * 1000; const cp = execa(cli.flags.command, { shell: true }); const target = parseInt(cli.flags.patternCount || '1', 10); cp.stdout.on('data', data => { process.stdout.write(data); const matches = multimatch([String(data)], cli.flags.pattern); const errMatches = multimatch([String(data)], cli.flags.errorPattern); if (matches.length > 0) { count++; } if (errMatches.length > 0) { process.exit(1); } if (count >= target) { setTimeout(() => { process.exit(0); }, duration); } }); cp.on('exit', e => { const elapsed = Date.now() - start; if (elapsed >= duration) { return; } setTimeout(() => { process.exit(e.exitCode); }, duration - elapsed); }); }
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/tasks/cra.js
tasks/cra.js
#!/usr/bin/env node /** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; const fs = require('fs'); const path = require('path'); const cp = require('child_process'); const cleanup = () => { console.log('Cleaning up.'); // Reset changes made to package.json files. cp.execSync(`git checkout -- packages/*/package.json`); // Uncomment when snapshot testing is enabled by default: // rm ./template/src/__snapshots__/App.test.js.snap }; const handleExit = () => { cleanup(); console.log('Exiting without error.'); process.exit(); }; const handleError = e => { console.error('ERROR! An error was encountered while executing'); console.error(e); cleanup(); console.log('Exiting with error.'); process.exit(1); }; process.on('SIGINT', handleExit); process.on('uncaughtException', handleError); console.log(); console.log('-------------------------------------------------------'); console.log('Assuming you have already run `npm install` to update the deps.'); console.log('If not, remember to do this before testing!'); console.log('-------------------------------------------------------'); console.log(); // Temporarily overwrite package.json of all packages in monorepo // to point to each other using absolute file:/ URLs. const gitStatus = cp.execSync(`git status --porcelain`).toString(); if (gitStatus.trim() !== '') { console.log('Please commit your changes before running this script!'); console.log('Exiting because `git status` is not empty:'); console.log(); console.log(gitStatus); console.log(); process.exit(1); } const rootDir = path.join(__dirname, '..'); const packagesDir = path.join(rootDir, 'packages'); const packagePathsByName = {}; fs.readdirSync(packagesDir).forEach(name => { const packageDir = path.join(packagesDir, name); const packageJson = path.join(packageDir, 'package.json'); if (fs.existsSync(packageJson)) { packagePathsByName[name] = packageDir; } }); Object.keys(packagePathsByName).forEach(name => { const packageJson = path.join(packagePathsByName[name], 'package.json'); const json = JSON.parse(fs.readFileSync(packageJson, 'utf8')); Object.keys(packagePathsByName).forEach(otherName => { if (json.dependencies && json.dependencies[otherName]) { json.dependencies[otherName] = 'file:' + packagePathsByName[otherName]; } if (json.devDependencies && json.devDependencies[otherName]) { json.devDependencies[otherName] = 'file:' + packagePathsByName[otherName]; } if (json.peerDependencies && json.peerDependencies[otherName]) { json.peerDependencies[otherName] = 'file:' + packagePathsByName[otherName]; } if (json.optionalDependencies && json.optionalDependencies[otherName]) { json.optionalDependencies[otherName] = 'file:' + packagePathsByName[otherName]; } }); fs.writeFileSync(packageJson, JSON.stringify(json, null, 2), 'utf8'); console.log( 'Replaced local dependencies in packages/' + name + '/package.json' ); }); console.log('Replaced all local dependencies for testing.'); console.log('Do not edit any package.json while this task is running.'); // Finally, pack react-scripts. // Don't redirect stdio as we want to capture the output that will be returned // from execSync(). In this case it will be the .tgz filename. const scriptsFileName = cp .execSync(`npm pack`, { cwd: path.join(packagesDir, 'react-scripts') }) .toString() .trim(); const scriptsPath = path.join(packagesDir, 'react-scripts', scriptsFileName); const args = process.argv.slice(2); // Now run the CRA command const craScriptPath = path.join(packagesDir, 'create-react-app', 'index.js'); cp.execSync( `node ${craScriptPath} ${args.join(' ')} --scripts-version="${scriptsPath}"`, { cwd: rootDir, stdio: 'inherit', } ); // Cleanup handleExit();
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/tasks/screencast.js
tasks/screencast.js
#!/usr/bin/env node /** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; const fs = require('fs'); const path = require('path'); const execa = require('execa'); const tempy = require('tempy'); main(); function main() { const previous = process.cwd(); const cwd = tempy.directory(); const cast = path.join(cwd, 'screencast.json'); const script = path.join(__dirname, 'screencast.sh'); const out = path.join(previous, 'screencast.svg'); const resolveLine = l => l.indexOf('🔍 Resolving packages...') > -1; const fetchLine = l => l.indexOf('🚚 Fetching packages...') > -1; const countLine = l => l.match(/Saved [0-9]+ new dependencies/); const doneLine = l => l.indexOf('✨ Done in') > -1; try { process.chdir(cwd); console.log(`Recording screencast ...`); execa.sync('asciinema', ['rec', '--command', `sh ${script}`, cast], { cwd, stdio: 'inherit', }); console.log('Cleaning data ...'); const data = require(cast); cut(data.stdout, { start: resolveLine, end: fetchLine }); cut(data.stdout, { start: countLine, end: doneLine }); replace(data.stdout, [{ in: cwd, out: '~' }]); fs.writeFileSync(cast, JSON.stringify(data, null, ' ')); console.log('Rendering SVG ...'); execa.sync('svg-term', ['--window', '--in', cast, '--out', out]); console.log(`Recorded screencast to ${cast}`); console.log(`Rendered SVG to ${out}`); } finally { process.chdir(previous); } } function cut(frames, { start, end }) { const si = frames.findIndex(([, l]) => start(l)); const ei = frames.findIndex(([, l]) => end(l)); if (si === -1 || ei === -1) { return; } frames.splice(si + 1, ei - si - 1); } function replace(frames, replacements) { frames.forEach(frame => { replacements.forEach(r => (frame[1] = frame[1].split(r.in).join(r.out))); }); }
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/jest.config.js
test/jest.config.js
'use strict'; module.exports = { testEnvironment: 'node', testMatch: ['<rootDir>/**/*.test.js'], testPathIgnorePatterns: ['/src/', 'node_modules'], };
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/integration/create-react-app/index.test.js
test/integration/create-react-app/index.test.js
'use strict'; const execa = require('execa'); const { mkdirp, writeFileSync, existsSync, readdirSync } = require('fs-extra'); const { join } = require('path'); const { rmSync } = require('fs'); const cli = require.resolve('create-react-app/index.js'); // Increase the timeout for GitHub macOS runner jest.setTimeout(1000 * 60 * (process.env.RUNNER_OS === 'macOS' ? 10 : 5)); const projectName = 'test-app'; const genPath = join(__dirname, projectName); const generatedFiles = [ '.gitignore', 'README.md', 'node_modules', 'package.json', 'public', 'src', 'package-lock.json', ]; const removeGenPath = () => { rmSync(genPath, { recursive: true, force: true, }); }; beforeEach(removeGenPath); afterAll(async () => { removeGenPath(); // Defer jest result output waiting for stdout to flush await new Promise(resolve => setTimeout(resolve, 100)); }); const run = async (args, options) => { process.stdout.write( `::group::Test "${ expect.getState().currentTestName }" - "create-react-app ${args.join(' ')}" output:\n` ); const result = execa('node', [cli].concat(args), options); result.stdout.on('data', chunk => process.stdout.write(chunk.toString('utf8')) ); const childProcessResult = await result; process.stdout.write(`ExitCode: ${childProcessResult.exitCode}\n`); process.stdout.write('::endgroup::\n'); const files = existsSync(genPath) ? readdirSync(genPath).filter(f => existsSync(join(genPath, f))) : null; return { ...childProcessResult, files, }; }; const expectAllFiles = (arr1, arr2) => expect([...arr1].sort()).toEqual([...arr2].sort()); describe('create-react-app', () => { it('check yarn installation', async () => { const { exitCode } = await execa('yarn', ['--version']); // Assert for exit code expect(exitCode).toBe(0); }); it('asks to supply an argument if none supplied', async () => { const { exitCode, stderr, files } = await run([], { reject: false }); // Assertions expect(exitCode).toBe(1); expect(stderr).toContain('Please specify the project directory'); expect(files).toBe(null); }); it('creates a project on supplying a name as the argument', async () => { const { exitCode, files } = await run([projectName], { cwd: __dirname }); // Assert for exit code expect(exitCode).toBe(0); // Assert for the generated files expectAllFiles(files, generatedFiles); }); it('warns about conflicting files in path', async () => { // Create the temporary directory await mkdirp(genPath); // Create a package.json file const pkgJson = join(genPath, 'package.json'); writeFileSync(pkgJson, '{ "foo": "bar" }'); const { exitCode, stdout, files } = await run([projectName], { cwd: __dirname, reject: false, }); // Assert for exit code expect(exitCode).toBe(1); // Assert for the expected message expect(stdout).toContain( `The directory ${projectName} contains files that could conflict` ); // Existing file is still there expectAllFiles(files, ['package.json']); }); it('creates a project in the current directory', async () => { // Create temporary directory await mkdirp(genPath); // Create a project in the current directory const { exitCode, files } = await run(['.'], { cwd: genPath }); // Assert for exit code expect(exitCode).toBe(0); // Assert for the generated files expectAllFiles(files, generatedFiles); }); it('uses yarn as the package manager', async () => { const { exitCode, files } = await run([projectName], { cwd: __dirname, env: { npm_config_user_agent: 'yarn' }, }); // Assert for exit code expect(exitCode).toBe(0); // Assert for the generated files const generatedFilesWithYarn = generatedFiles.map(file => file === 'package-lock.json' ? 'yarn.lock' : file ); expectAllFiles(files, generatedFilesWithYarn); }); it('creates a project based on the typescript template', async () => { const { exitCode, files } = await run( [projectName, '--template', 'typescript'], { cwd: __dirname, } ); // Assert for exit code expect(exitCode).toBe(0); // Assert for the generated files // TODO: why is there no tsconfig.json file on the template? expectAllFiles(files, generatedFiles); }); });
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/issue-5176-flow-class-properties/index.test.js
test/fixtures/issue-5176-flow-class-properties/index.test.js
'use strict'; const testSetup = require('../__shared__/test-setup'); test('passes tests', async () => { const { fulfilled } = await testSetup.scripts.test({ jestEnvironment: 'node', }); expect(fulfilled).toBe(true); });
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/issue-5176-flow-class-properties/src/App.test.js
test/fixtures/issue-5176-flow-class-properties/src/App.test.js
import App from './App'; it('creates instance without', () => { const app = new App(); expect(app.foo()).toBe('bar'); });
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/issue-5176-flow-class-properties/src/App.js
test/fixtures/issue-5176-flow-class-properties/src/App.js
class App { constructor() { this.foo = this.foo.bind(this); } foo: void => void; foo() { return 'bar'; } } export default App;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/jsconfig/index.test.js
test/fixtures/jsconfig/index.test.js
'use strict'; const testSetup = require('../__shared__/test-setup'); test('builds in development', async () => { const { fulfilled } = await testSetup.scripts.start({ smoke: true }); expect(fulfilled).toBe(true); }); test('builds in production', async () => { const { fulfilled } = await testSetup.scripts.build(); expect(fulfilled).toBe(true); }); test('passes tests', async () => { const { fulfilled } = await testSetup.scripts.test(); expect(fulfilled).toBe(true); });
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/jsconfig/src/App.test.js
test/fixtures/jsconfig/src/App.test.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; test('loads modules absolutely with baseUrl', () => { const div = document.createElement('div'); return new Promise(resolve => { ReactDOM.render(<App onReady={resolve} />, div); }); });
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/jsconfig/src/absoluteLoad.js
test/fixtures/jsconfig/src/absoluteLoad.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const absoluteLoad = () => [ { id: 1, name: '1' }, { id: 2, name: '2' }, { id: 3, name: '3' }, { id: 4, name: '4' }, ]; export default absoluteLoad;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/jsconfig/src/index.js
test/fixtures/jsconfig/src/index.js
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/jsconfig/src/App.js
test/fixtures/jsconfig/src/App.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import load from 'absoluteLoad'; export default class App extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load(); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div> {this.state.users.map(user => ( <div key={user.id}>{user.name}</div> ))} </div> ); } }
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/__shared__/test-setup.js
test/fixtures/__shared__/test-setup.js
'use strict'; const path = require('path'); const fs = require('fs-extra'); const TestSetup = require('./util/setup'); const fixturePath = path.dirname(module.parent.filename); const fixtureName = path.basename(fixturePath); const disablePnp = fs.existsSync(path.resolve(fixturePath, '.disable-pnp')); const testSetup = new TestSetup(fixtureName, fixturePath, { pnp: !disablePnp, }); beforeAll(async () => { await testSetup.setup(); }, 1000 * 60 * 5); afterAll(async () => { await testSetup.teardown(); }); beforeEach(() => jest.setTimeout(1000 * 60 * 5)); module.exports = testSetup;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/__shared__/util/setup.js
test/fixtures/__shared__/util/setup.js
'use strict'; const execa = require('execa'); const fs = require('fs-extra'); const path = require('path'); const tempy = require('tempy'); const ReactScripts = require('./scripts'); module.exports = class TestSetup { constructor(fixtureName, templateDirectory) { this.fixtureName = fixtureName; this.templateDirectory = templateDirectory; this.testDirectory = null; this._scripts = null; this.setup = this.setup.bind(this); this.teardown = this.teardown.bind(this); this.isLocal = !(process.env.CI && process.env.CI !== 'false'); } async setup() { await this.teardown(); this.testDirectory = tempy.directory(); await fs.copy( path.resolve(__dirname, '..', 'template'), this.testDirectory ); await fs.copy(this.templateDirectory, this.testDirectory); await fs.remove(path.resolve(this.testDirectory, 'test.partial.js')); const packageJson = await fs.readJson( path.resolve(this.testDirectory, 'package.json') ); const shouldInstallScripts = !this.isLocal; if (shouldInstallScripts) { packageJson.dependencies = Object.assign({}, packageJson.dependencies, { 'react-scripts': 'latest', }); } packageJson.scripts = Object.assign({}, packageJson.scripts, { start: 'react-scripts start', build: 'react-scripts build', test: 'react-scripts test', }); packageJson.license = packageJson.license || 'UNLICENSED'; await fs.writeJson( path.resolve(this.testDirectory, 'package.json'), packageJson ); await execa('npm', ['install'], { cwd: this.testDirectory, }); if (!shouldInstallScripts) { await fs.ensureSymlink( path.resolve( path.resolve( __dirname, '../../../..', 'packages', 'react-scripts', 'bin', 'react-scripts.js' ) ), path.join(this.testDirectory, 'node_modules', '.bin', 'react-scripts') ); await execa('npm', ['link', 'react-scripts'], { cwd: this.testDirectory, }); } } get scripts() { if (this.testDirectory == null) { return null; } if (this._scripts == null) { this._scripts = new ReactScripts(this.testDirectory); } return this._scripts; } async teardown() { if (this.testDirectory != null) { try { await fs.remove(this.testDirectory); } catch (ex) { if (this.isLocal) { throw ex; } else { // In CI, don't worry if the test directory was not able to be deleted } } this.testDirectory = null; this._scripts = null; } } };
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/__shared__/util/scripts.js
test/fixtures/__shared__/util/scripts.js
'use strict'; const execa = require('execa'); const getPort = require('get-port'); const stripAnsi = require('strip-ansi'); const waitForLocalhost = require('wait-for-localhost'); function execaSafe(...args) { return execa(...args) .then(({ stdout, stderr, ...rest }) => ({ fulfilled: true, rejected: false, stdout: stripAnsi(stdout), stderr: stripAnsi(stderr), ...rest, })) .catch(err => ({ fulfilled: false, rejected: true, reason: err, stdout: '', stderr: stripAnsi(err.message.split('\n').slice(2).join('\n')), })); } module.exports = class ReactScripts { constructor(root) { this.root = root; } async start({ smoke = false, env = {} } = {}) { const port = await getPort(); const options = { cwd: this.root, env: Object.assign( {}, { CI: 'false', FORCE_COLOR: '0', BROWSER: 'none', PORT: port, }, env ), }; if (smoke) { return await execaSafe('npm', ['start', '--smoke-test'], options); } const startProcess = execa('npm', ['start'], options); await waitForLocalhost({ port }); return { port, done() { startProcess.kill('SIGKILL'); }, }; } async build({ env = {} } = {}) { return await execaSafe('npm', ['run', 'build'], { cwd: this.root, env: Object.assign({}, { CI: 'false', FORCE_COLOR: '0' }, env), }); } async serve() { const port = await getPort(); const serveProcess = execa( 'npm', ['run', 'serve', '--', '-p', port, '-s', 'build/'], { cwd: this.root, } ); await waitForLocalhost({ port }); return { port, done() { serveProcess.kill('SIGKILL'); }, }; } async test({ jestEnvironment = 'jsdom', env = {} } = {}) { return await execaSafe('npm', ['test', '--env', jestEnvironment, '--ci'], { cwd: this.root, env: Object.assign({}, { CI: 'true' }, env), }); } };
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/typescript-typecheck/index.test.js
test/fixtures/typescript-typecheck/index.test.js
'use strict'; const testSetup = require('../__shared__/test-setup'); const puppeteer = require('puppeteer'); const expectedErrorMsg = `Argument of type '123' is not assignable to parameter of type 'string'`; test('shows error overlay in browser', async () => { const { port, done } = await testSetup.scripts.start(); const browser = await puppeteer.launch({ headless: true }); try { const page = await browser.newPage(); await page.goto(`http://localhost:${port}/`); await page.waitForSelector('iframe', { timeout: 5000 }); const overlayMsg = await page.evaluate(() => { const overlay = document.querySelector('iframe').contentWindow; return overlay.document.body.innerHTML; }); expect(overlayMsg).toContain(expectedErrorMsg); } finally { browser.close(); done(); } }); test('shows error in console (dev mode)', async () => { const { stderr } = await testSetup.scripts.start({ smoke: true }); expect(stderr).toContain(expectedErrorMsg); }); test('shows error in console (prod mode)', async () => { const { stderr } = await testSetup.scripts.build(); expect(stderr).toContain(expectedErrorMsg); });
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/boostrap-sass/index.test.js
test/fixtures/boostrap-sass/index.test.js
'use strict'; const testSetup = require('../__shared__/test-setup'); if (testSetup.isLocal) { // TODO: make this work locally test('skipped locally', () => {}); } else { test('builds in development', async () => { const { fulfilled } = await testSetup.scripts.start({ smoke: true }); expect(fulfilled).toBe(true); }); test('builds in production', async () => { const { fulfilled } = await testSetup.scripts.build(); expect(fulfilled).toBe(true); }); }
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/boostrap-sass/src/index.js
test/fixtures/boostrap-sass/src/index.js
import React from 'react'; import ReactDOM from 'react-dom'; import './index.sass'; ReactDOM.render(<div />, document.getElementById('root'));
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/typescript-advanced/index.test.js
test/fixtures/typescript-advanced/index.test.js
'use strict'; const testSetup = require('../__shared__/test-setup'); test('builds in development', async () => { const { fulfilled } = await testSetup.scripts.start({ smoke: true }); expect(fulfilled).toBe(true); }); test('builds in production', async () => { const { fulfilled } = await testSetup.scripts.build(); expect(fulfilled).toBe(true); }); test('passes tests', async () => { const { fulfilled } = await testSetup.scripts.test({ jestEnvironment: 'node', }); expect(fulfilled).toBe(true); });
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/mjs-support/index.test.js
test/fixtures/mjs-support/index.test.js
'use strict'; const testSetup = require('../__shared__/test-setup'); const puppeteer = require('puppeteer'); test('can use mjs library in development', async () => { const { port, done } = await testSetup.scripts.start(); const browser = await puppeteer.launch({ headless: true }); try { const page = await browser.newPage(); await page.goto(`http://localhost:${port}/`); await page.waitForSelector('.mjs-gql-result', { timeout: 0 }); const output = await page.evaluate(() => { return Array.from(document.getElementsByClassName('mjs-gql-result')).pop() .innerHTML; }); expect(output).toMatchSnapshot(); } finally { browser.close(); done(); } }); test('can use mjs library in production', async () => { await testSetup.scripts.build(); const { port, done } = await testSetup.scripts.serve(); const browser = await puppeteer.launch({ headless: true }); try { const page = await browser.newPage(); await page.goto(`http://localhost:${port}/`); await page.waitForSelector('.mjs-gql-result', { timeout: 0 }); const output = await page.evaluate(() => { return Array.from(document.getElementsByClassName('mjs-gql-result')).pop() .innerHTML; }); expect(output).toMatchSnapshot(); } finally { browser.close(); done(); } });
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/mjs-support/src/index.js
test/fixtures/mjs-support/src/index.js
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/mjs-support/src/App.js
test/fixtures/mjs-support/src/App.js
import React, { Component } from 'react'; import { graphql, GraphQLSchema, GraphQLObjectType, GraphQLString, } from 'graphql'; const schema = new GraphQLSchema({ query: new GraphQLObjectType({ name: 'RootQueryType', fields: { hello: { type: GraphQLString, resolve() { return 'world'; }, }, }, }), }); class App extends Component { state = {}; componentDidMount() { graphql(schema, '{ hello }').then(({ data }) => { this.setState({ result: data.hello }); }); } render() { const { result } = this.state; return result ? <div className="mjs-gql-result">{result}</div> : null; } } export default App;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/test/fixtures/global-scss-asset-resolution/index.test.js
test/fixtures/global-scss-asset-resolution/index.test.js
'use strict'; const testSetup = require('../__shared__/test-setup'); if (testSetup.isLocal) { // TODO: make this work locally test('skipped locally', () => {}); } else { test('builds in development', async () => { const { fulfilled } = await testSetup.scripts.start({ smoke: true }); expect(fulfilled).toBe(true); }); test('builds in production', async () => { const { fulfilled } = await testSetup.scripts.build(); expect(fulfilled).toBe(true); }); }
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false