Using Javascript to do comparison of user inputs - javascript

I have the following code that is using 3 columns to check for difference in input values.
The third column difference in my view is generated fine but while viewing it the table is not displaying it.
What is want to do is to compare base text with new text and thrid text input enteries and display the changes to user in inline or side by side format
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<title>jsdifflib demo</title>
<link rel="stylesheet" type="text/css" href="diffview.css"/>
<script type="text/javascript" src="diffview.js"></script>
<script type="text/javascript" src="difflib.js"></script>
<style type="text/css">
body {
font-size: 12px;
font-family: Sans-Serif,serif;
}
h2 {
margin: 0.5em 0 0.1em;
text-align: center;
}
.top {
text-align: center;
}
.textInput {
display: block;
width: 49%;
float: left;
}
textarea {
width:100%;
height:300px;
}
label:hover {
text-decoration: underline;
cursor: pointer;
}
.spacer {
margin-left: 10px;
}
.viewType {
font-size: 16px;
clear: both;
text-align: center;
padding: 1em;
}
#diffoutput {
width: 100%;
}
</style>
<script type="text/javascript">
function diffUsingJS(viewType) {
"use strict";
var byId = function (id) { return document.getElementById(id); },
base = difflib.stringAsLines(byId("baseText").value),
newtxt = difflib.stringAsLines(byId("newText").value),
thirdText = difflib.stringAsLines(byId("3rdText").value),
sm = new difflib.SequenceMatcher(base, newtxt, thirdText),
opcodes = sm.get_opcodes(),
diffoutputdiv = byId("diffoutput"),
contextSize = byId("contextSize").value;
diffoutputdiv.innerHTML = "";
contextSize = contextSize || null;
diffoutputdiv.appendChild(diffview.buildView({
baseTextLines: base,
newTextLines: newtxt,
thirdTextLines: thirdText,
opcodes: opcodes,
baseTextName: "Base Text",
newTextName: "New Text",
thirdTextName: "Third Text",
contextSize: contextSize,
viewType: viewType
}));
}
</script>
</head>
<body>
<div class="top">
<strong>Context size (optional):</strong> <input type="text" id="contextSize" value="" />
</div>
<div class="textInput">
<h2>Base Text</h2>
<textarea id="baseText" >a</textarea>
</div>
<div class="textInput spacer">
<h2>New Text</h2>
<textarea id="newText">b</textarea>
</div>
<div class="textInput spacer">
<h2>3rd Text</h2>
<textarea id="3rdText">c</textarea>
</div>
<div class="viewType">
<input type="radio" name="_viewtype" id="sidebyside" onclick="diffUsingJS(0);" /> <label for="sidebyside">Side by Side Diff</label>
<input type="radio" name="_viewtype" id="inline" onclick="diffUsingJS(1);" /> <label for="inline">Inline Diff</label>
</div>
<div id="diffoutput"> </div>
</body>
</html>
diffview.js
var diffview = {
/**
* Builds and returns a visual diff view. The single parameter, `params', should contain
* the following values:
*
* - baseTextLines: the array of strings that was used as the base text input to SequenceMatcher
* - newTextLines: the array of strings that was used as the new text input to SequenceMatcher
* - opcodes: the array of arrays returned by SequenceMatcher.get_opcodes()
* - baseTextName: the title to be displayed above the base text listing in the diff view; defaults
* to "Base Text"
* - newTextName: the title to be displayed above the new text listing in the diff view; defaults
* to "New Text"
* - contextSize: the number of lines of context to show around differences; by default, all lines
* are shown
* - viewType: if 0, a side-by-side diff view is generated (default); if 1, an inline diff view is
* generated
*/
buildView: function (params) {
var baseTextLines = params.baseTextLines;
var newTextLines = params.newTextLines;
var thirdTextLines = params.thirdTextLines;
var opcodes = params.opcodes;
var baseTextName = params.baseTextName ? params.baseTextName : "Base Text";
var newTextName = params.newTextName ? params.newTextName : "New Text";
var thirdTextName = params.thirdTextName ? params.thirdTextName: "Third Text"
var contextSize = params.contextSize;
var inline = (params.viewType == 0 || params.viewType == 1) ? params.viewType : 0;
if (baseTextLines == null)
throw "Cannot build diff view; baseTextLines is not defined.";
if (newTextLines == null)
throw "Cannot build diff view; newTextLines is not defined.";
if (thirdTextLines == null)
throw "Cannot build diff view; thirdTextLines is not defined.";
if (!opcodes)
throw "Canno build diff view; opcodes is not defined.";
function celt (name, clazz) {
var e = document.createElement(name);
e.className = clazz;
return e;
}
function telt (name, text) {
var e = document.createElement(name);
e.appendChild(document.createTextNode(text));
return e;
}
function ctelt (name, clazz, text) {
var e = document.createElement(name);
e.className = clazz;
e.appendChild(document.createTextNode(text));
return e;
}
var tdata = document.createElement("thead");
var node = document.createElement("tr");
tdata.appendChild(node);
if (inline) {
node.appendChild(document.createElement("th"));
node.appendChild(document.createElement("th"));
node.appendChild(ctelt("th", "texttitle", baseTextName + " vs. " + newTextName + " vs. " + thirdTextName));
} else {
node.appendChild(document.createElement("th"));
node.appendChild(ctelt("th", "texttitle", baseTextName));
node.appendChild(document.createElement("th"));
node.appendChild(ctelt("th", "texttitle", newTextName));
node.appendChild(document.createElement("th"));
node.appendChild(ctelt("th", "texttitle", thirdTextName));
}
tdata = [tdata];
var rows = [];
var node2;
/**
* Adds two cells to the given row; if the given row corresponds to a real
* line number (based on the line index tidx and the endpoint of the
* range in question tend), then the cells will contain the line number
* and the line of text from textLines at position tidx (with the class of
* the second cell set to the name of the change represented), and tidx + 1 will
* be returned. Otherwise, tidx is returned, and two empty cells are added
* to the given row.
*/
function addCells (row, tidx, tend, textLines, change) {
if (tidx < tend) {
row.appendChild(telt("th", (tidx + 1).toString()));
row.appendChild(ctelt("td", change, textLines[tidx].replace(/\t/g, "\u00a0\u00a0\u00a0\u00a0")));
return tidx + 1;
} else {
row.appendChild(document.createElement("th"));
row.appendChild(celt("td", "empty"));
return tidx;
}
}
function addCellsInline (row, tidx, tidx2, textLines, change) {
row.appendChild(telt("th", tidx == null ? "" : (tidx + 1).toString()));
row.appendChild(telt("th", tidx2 == null ? "" : (tidx2 + 1).toString()));
row.appendChild(ctelt("td", change, textLines[tidx != null ? tidx : tidx2].replace(/\t/g, "\u00a0\u00a0\u00a0\u00a0")));
}
for (var idx = 0; idx < opcodes.length; idx++) {
code = opcodes[idx];
change = code[0];
var b = code[1];
var be = code[2];
var n = code[3];
var ne = code[4];
var rowcnt = Math.max(be - b, ne - n);
var toprows = [];
var botrows = [];
for (var i = 0; i < rowcnt; i++) {
// jump ahead if we've alredy provided leading context or if this is the first range
if (contextSize && opcodes.length > 1 && ((idx > 0 && i == contextSize) || (idx == 0 && i == 0)) && change=="equal") {
var jump = rowcnt - ((idx == 0 ? 1 : 2) * contextSize);
if (jump > 1) {
toprows.push(node = document.createElement("tr"));
b += jump;
n += jump;
i += jump - 1;
node.appendChild(telt("th", "..."));
if (!inline) node.appendChild(ctelt("td", "skip", ""));
node.appendChild(telt("th", "..."));
node.appendChild(ctelt("td", "skip", ""));
// skip last lines if they're all equal
if (idx + 1 == opcodes.length) {
break;
} else {
continue;
}
}
}
toprows.push(node = document.createElement("tr"));
if (inline) {
if (change == "insert") {
addCellsInline(node, null, n++, newTextLines, change);
} else if (change == "replace") {
botrows.push(node2 = document.createElement("tr"));
if (b < be) addCellsInline(node, b++, null, baseTextLines, "delete");
if (n < ne) addCellsInline(node2, null, n++, newTextLines, "insert");
if (n < ne) addCellsInline(node2, null, n++, thirdTextLines, "insert");
} else if (change == "delete") {
addCellsInline(node, b++, null, baseTextLines, change);
} else {
// equal
addCellsInline(node, b++, n++, baseTextLines, change);
}
} else {
b = addCells(node, b, be, baseTextLines, change);
n = addCells(node, n, ne, newTextLines, change);
n = addCells(node, n, ne, thirdTextLines, change);
}
}
for (var i = 0; i < toprows.length; i++) rows.push(toprows[i]);
for (var i = 0; i < botrows.length; i++) rows.push(botrows[i]);
}
tdata.push(node = document.createElement("tbody"));
for (var idx in rows) rows.hasOwnProperty(idx) && node.appendChild(rows[idx]);
node = celt("table", "diff" + (inline ? " inlinediff" : ""));
for (var idx in tdata) tdata.hasOwnProperty(idx) && node.appendChild(tdata[idx]);
return node;
}
};
difflib.js
var __whitespace = {" ":true, "\t":true, "\n":true, "\f":true, "\r":true};
var difflib = {
defaultJunkFunction: function (c) {
return __whitespace.hasOwnProperty(c);
},
stripLinebreaks: function (str) { return str.replace(/^[\n\r]*|[\n\r]*$/g, ""); },
stringAsLines: function (str) {
var lfpos = str.indexOf("\n");
var crpos = str.indexOf("\r");
var linebreak = ((lfpos > -1 && crpos > -1) || crpos < 0) ? "\n" : "\r";
var lines = str.split(linebreak);
for (var i = 0; i < lines.length; i++) {
lines[i] = difflib.stripLinebreaks(lines[i]);
}
return lines;
},
// iteration-based reduce implementation
__reduce: function (func, list, initial) {
if (initial != null) {
var value = initial;
var idx = 0;
} else if (list) {
var value = list[0];
var idx = 1;
} else {
return null;
}
for (; idx < list.length; idx++) {
value = func(value, list[idx]);
}
return value;
},
// comparison function for sorting lists of numeric tuples
__ntuplecomp: function (a, b) {
var mlen = Math.max(a.length, b.length);
for (var i = 0; i < mlen; i++) {
if (a[i] < b[i]) return -1;
if (a[i] > b[i]) return 1;
}
return a.length == b.length ? 0 : (a.length < b.length ? -1 : 1);
},
__calculate_ratio: function (matches, length) {
return length ? 2.0 * matches / length : 1.0;
},
// returns a function that returns true if a key passed to the returned function
// is in the dict (js object) provided to this function; replaces being able to
// carry around dict.has_key in python...
__isindict: function (dict) {
return function (key) { return dict.hasOwnProperty(key); };
},
// replacement for python's dict.get function -- need easy default values
__dictget: function (dict, key, defaultValue) {
return dict.hasOwnProperty(key) ? dict[key] : defaultValue;
},
SequenceMatcher: function (a, b, c, isjunk) {
this.set_seqs = function (a, b, c, ) {
this.set_seq1(a);
this.set_seq2(b);
this.set_seq3(c);
}
this.set_seq1 = function (a) {
if (a == this.a) return;
this.a = a;
this.matching_blocks = this.opcodes = null;
}
this.set_seq2 = function (b) {
console.log("Value in set ", b)
if (b == this.b) return;
this.b = b;
this.matching_blocks = this.opcodes = this.fullbcount = null;
this.__chain_b();
}
this.set_seq3 = function (c) {
console.log("Value in set ", c)
if (c == this.c) return;
this.c = c;
this.matching_blocks = this.opcodes = this.fullbcount = null;
this.__chain_c();
}
this.__chain_c = function () {
console.log("This is ", this.c)
var c = this.c;
var n = c.length;
var c2j = this.c2j = {};
var populardict = {};
for (var i = 0; i < c.length; i++) {
var celt = c[i];
if (c2j.hasOwnProperty(celt)) {
var indices = c2j[elt];
if (n >= 200 && indices.length * 100 > n) {
populardict[celt] = 1;
delete c2j[celt];
} else {
indices.push(i);
}
} else {
c2j[celt] = [i];
}
}
for (var elt in populardict) {
if (populardict.hasOwnProperty(elt)) {
delete c2j[elt];
}
}
var isjunk = this.isjunk;
var junkdict = {};
if (isjunk) {
for (var elt in populardict) {
if (populardict.hasOwnProperty(elt) && isjunk(elt)) {
junkdict[elt] = 1;
delete populardict[elt];
}
}
for (var elt in c2j) {
if (c2j.hasOwnProperty(elt) && isjunk(elt)) {
junkdict[elt] = 1;
delete c2j[elt];
}
}
}
this.iscjunk = difflib.__isindict(junkdict);
this.iscpopular = difflib.__isindict(populardict);
}
this.__chain_b = function () {
var b = this.b;
var n = b.length;
var b2j = this.b2j = {};
var populardict = {};
for (var i = 0; i < b.length; i++) {
var elt = b[i];
if (b2j.hasOwnProperty(elt)) {
var indices = b2j[elt];
if (n >= 200 && indices.length * 100 > n) {
populardict[elt] = 1;
delete b2j[elt];
} else {
indices.push(i);
}
} else {
b2j[elt] = [i];
}
}
for (var elt in populardict) {
if (populardict.hasOwnProperty(elt)) {
delete b2j[elt];
}
}
var isjunk = this.isjunk;
var junkdict = {};
if (isjunk) {
for (var elt in populardict) {
if (populardict.hasOwnProperty(elt) && isjunk(elt)) {
junkdict[elt] = 1;
delete populardict[elt];
}
}
for (var elt in b2j) {
if (b2j.hasOwnProperty(elt) && isjunk(elt)) {
junkdict[elt] = 1;
delete b2j[elt];
}
}
}
this.isbjunk = difflib.__isindict(junkdict);
this.isbpopular = difflib.__isindict(populardict);
}
this.find_longest_match = function (alo, ahi, blo, bhi) {
var a = this.a;
var b = this.b;
var b2j = this.b2j;
var isbjunk = this.isbjunk;
var besti = alo;
var bestj = blo;
var bestsize = 0;
var j = null;
var k;
var j2len = {};
var nothing = [];
for (var i = alo; i < ahi; i++) {
var newj2len = {};
var jdict = difflib.__dictget(b2j, a[i], nothing);
for (var jkey in jdict) {
if (jdict.hasOwnProperty(jkey)) {
j = jdict[jkey];
if (j < blo) continue;
if (j >= bhi) break;
newj2len[j] = k = difflib.__dictget(j2len, j - 1, 0) + 1;
if (k > bestsize) {
besti = i - k + 1;
bestj = j - k + 1;
bestsize = k;
}
}
}
j2len = newj2len;
}
while (besti > alo && bestj > blo && !isbjunk(b[bestj - 1]) && a[besti - 1] == b[bestj - 1]) {
besti--;
bestj--;
bestsize++;
}
while (besti + bestsize < ahi && bestj + bestsize < bhi &&
!isbjunk(b[bestj + bestsize]) &&
a[besti + bestsize] == b[bestj + bestsize]) {
bestsize++;
}
while (besti > alo && bestj > blo && isbjunk(b[bestj - 1]) && a[besti - 1] == b[bestj - 1]) {
besti--;
bestj--;
bestsize++;
}
while (besti + bestsize < ahi && bestj + bestsize < bhi && isbjunk(b[bestj + bestsize]) &&
a[besti + bestsize] == b[bestj + bestsize]) {
bestsize++;
}
return [besti, bestj, bestsize];
}
this.get_matching_blocks = function () {
if (this.matching_blocks != null) return this.matching_blocks;
var la = this.a.length;
var lb = this.b.length;
var queue = [[0, la, 0, lb]];
var matching_blocks = [];
var alo, ahi, blo, bhi, qi, i, j, k, x;
while (queue.length) {
qi = queue.pop();
alo = qi[0];
ahi = qi[1];
blo = qi[2];
bhi = qi[3];
x = this.find_longest_match(alo, ahi, blo, bhi);
i = x[0];
j = x[1];
k = x[2];
if (k) {
matching_blocks.push(x);
if (alo < i && blo < j)
queue.push([alo, i, blo, j]);
if (i+k < ahi && j+k < bhi)
queue.push([i + k, ahi, j + k, bhi]);
}
}
matching_blocks.sort(difflib.__ntuplecomp);
var i1 = 0, j1 = 0, k1 = 0, block = 0;
var i2, j2, k2;
var non_adjacent = [];
for (var idx in matching_blocks) {
if (matching_blocks.hasOwnProperty(idx)) {
block = matching_blocks[idx];
i2 = block[0];
j2 = block[1];
k2 = block[2];
if (i1 + k1 == i2 && j1 + k1 == j2) {
k1 += k2;
} else {
if (k1) non_adjacent.push([i1, j1, k1]);
i1 = i2;
j1 = j2;
k1 = k2;
}
}
}
if (k1) non_adjacent.push([i1, j1, k1]);
non_adjacent.push([la, lb, 0]);
this.matching_blocks = non_adjacent;
return this.matching_blocks;
}
this.get_opcodes = function () {
if (this.opcodes != null) return this.opcodes;
var i = 0;
var j = 0;
var answer = [];
this.opcodes = answer;
var block, ai, bj, size, tag;
var blocks = this.get_matching_blocks();
for (var idx in blocks) {
if (blocks.hasOwnProperty(idx)) {
block = blocks[idx];
ai = block[0];
bj = block[1];
size = block[2];
tag = '';
if (i < ai && j < bj) {
tag = 'replace';
} else if (i < ai) {
tag = 'delete';
} else if (j < bj) {
tag = 'insert';
}
if (tag) answer.push([tag, i, ai, j, bj]);
i = ai + size;
j = bj + size;
if (size) answer.push(['equal', ai, i, bj, j]);
}
}
return answer;
}
// this is a generator function in the python lib, which of course is not supported in javascript
// the reimplementation builds up the grouped opcodes into a list in their entirety and returns that.
this.get_grouped_opcodes = function (n) {
if (!n) n = 3;
var codes = this.get_opcodes();
if (!codes) codes = [["equal", 0, 1, 0, 1]];
var code, tag, i1, i2, j1, j2;
if (codes[0][0] == 'equal') {
code = codes[0];
tag = code[0];
i1 = code[1];
i2 = code[2];
j1 = code[3];
j2 = code[4];
codes[0] = [tag, Math.max(i1, i2 - n), i2, Math.max(j1, j2 - n), j2];
}
if (codes[codes.length - 1][0] == 'equal') {
code = codes[codes.length - 1];
tag = code[0];
i1 = code[1];
i2 = code[2];
j1 = code[3];
j2 = code[4];
codes[codes.length - 1] = [tag, i1, Math.min(i2, i1 + n), j1, Math.min(j2, j1 + n)];
}
var nn = n + n;
var group = [];
var groups = [];
for (var idx in codes) {
if (codes.hasOwnProperty(idx)) {
code = codes[idx];
tag = code[0];
i1 = code[1];
i2 = code[2];
j1 = code[3];
j2 = code[4];
if (tag == 'equal' && i2 - i1 > nn) {
group.push([tag, i1, Math.min(i2, i1 + n), j1, Math.min(j2, j1 + n)]);
groups.push(group);
group = [];
i1 = Math.max(i1, i2-n);
j1 = Math.max(j1, j2-n);
}
group.push([tag, i1, i2, j1, j2]);
}
}
if (group && !(group.length == 1 && group[0][0] == 'equal')) groups.push(group)
return groups;
}
this.ratio = function () {
matches = difflib.__reduce(
function (sum, triple) { return sum + triple[triple.length - 1]; },
this.get_matching_blocks(), 0);
return difflib.__calculate_ratio(matches, this.a.length + this.b.length);
}
this.quick_ratio = function () {
var fullbcount, elt;
if (this.fullbcount == null) {
this.fullbcount = fullbcount = {};
for (var i = 0; i < this.b.length; i++) {
elt = this.b[i];
fullbcount[elt] = difflib.__dictget(fullbcount, elt, 0) + 1;
}
}
fullbcount = this.fullbcount;
var avail = {};
var availhas = difflib.__isindict(avail);
var matches = numb = 0;
for (var i = 0; i < this.a.length; i++) {
elt = this.a[i];
if (availhas(elt)) {
numb = avail[elt];
} else {
numb = difflib.__dictget(fullbcount, elt, 0);
}
avail[elt] = numb - 1;
if (numb > 0) matches++;
}
return difflib.__calculate_ratio(matches, this.a.length + this.b.length);
}
this.real_quick_ratio = function () {
var la = this.a.length;
var lb = this.b.length;
return _calculate_ratio(Math.min(la, lb), la + lb);
}
this.isjunk = isjunk ? isjunk : difflib.defaultJunkFunction;
this.a = this.b = null;
this.set_seqs(a, b, c);
}
};

Related

Function return multiple value

I have this modified code here, how do I pass the argument?
function RNG(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function RCG() {
var char = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
var randomNumber = RNG(0, char.length - 1);
return char[randomNumber];
}
function Generator(n) {
var serialNumber;
var template = "0000-0000-0000-0000";
if (template != null) {
for (var i = 0; i < template.length; i++) {
var templateChar = template[i];
serialNumber += templateChar == "0" ? RCG() : templateChar;
}
}
return serialNumber;
}
console.log(Generator(5));
So when I enter 3 as the argument, the result will be like:
asda-asda-asda-asda
asda-asda-asda-asda
asda-asda-asda-asda
I think what you are asking is to be able to return 5 of these UUID from your method?
I have modified your Generator to return an array of UUIDs
function Generator(n) {
var template = "0000-0000-0000-0000";
var res = []; // declare an empty array
if (template != null) {
for (var j = 0; j < n; j++){
var serialNumber = "";
for (var i = 0; i < template.length; i++) {
var templateChar = template[i];
serialNumber += templateChar == "0" ? RCG() : templateChar;
}
res.push(serialNumber); // add uuid in the array
}
}
return res; // return the array
}
Output:
["1MYK-G2BB-YPG4-UYHU", "PWW1-6297-2VJX-56F2", "5U5B-A40D-9V43-WC6Y", "FQHQ-BU6A-CDS8-Y2J7", "23WK-1ASP-YA5Z-TS0R"]

vue show js 's error :TypeError: "this is undefined"

I want to make a dynamic water pipe with water flowing. The front picture is an error message.
The following picture is a method in the method in the vue page. I don't know if it will report an error. If you don't call this method, nothing will be reported.
The following code is the js file that introduces the vue page
//构造函数
function Createline(config) {
this.c = 0;
this.lines = [];
var self = this;
//初始化线
(function (self){
if(config.fx == "w"){
var number = config.canvas_w / (config.width + config.width/2 + config.jiange*2);
number = Math.ceil(number) + 1;
for(var n = 0 ; n < number ; n++){
var mxx = config.canvas_w - n*(config.width+config.width/2+config.jiange*2);
var lines_data = {
mx:mxx,
lx:mxx - config.width,
my:config.my,
ly:config.ly,
vx:config.vx,
vy:config.vy,
}
self.lines.push(lines_data);
var lines_data2 = {
mx:mxx-config.width-config.jiange,
lx:mxx-config.width-config.jiange-config.width/2,
my:config.my,
ly:config.ly,
vx:config.vx,
vy:config.vy,
}
self.lines.push(lines_data2);
}
}
if(config.fx == "h"){
var number = config.canvas_w / (config.width + config.width/2 + config.jiange*2);
number = Math.ceil(number) + 1;
for(var n = 0 ; n < number ; n++){
var myy = config.canvas_h - n*(config.width+config.width/2+config.jiange*2);
var lines_data3 = {
mx:config.mx,
lx:config.lx,
my:myy,
ly:myy - config.width,
vx:config.vx,
vy:config.vy,
}
self.lines.push(lines_data3);
var lines_data4 = {
mx:config.mx,
lx:config.lx,
my:myy-config.width-config.jiange,
ly:myy-config.width-config.jiange-config.width/2,
vx:config.vx,
vy:config.vy,
}
self.lines.push(lines_data4);
}
}
})(self);
}
//开始
Createline.prototype.begin = function (element,config) {
var canvasObj = document.getElementById(element);
var self = this;
var canvas = {
line_w: config.line_w || 3, //线条厚度
vx: config.vx || 0,//x轴运动速度
vy:config.vy || 0,//Y轴速度
color:config.color || "blue",//线条颜色
canvas_w:config.canvas_w || 0,//画布宽度
canvas_h:config.canvas_h || 0,//画布高度
mx: config.mx || 0,//线的开始位置X坐标
my: config.my || 0,//线的开始位置Y坐标
lx: config.lx || 0,//线的结束位置X坐标
ly: config.ly || 0,//线的结束位置Y坐标
fx:config.fx || "w",//运动方向 w 水平 ,h: 垂直
width:config.width || 20,//线的长度
jiange:config.jiange || 10, //线的间隔
}
if(canvasObj.getContext("2d")){
canvas.ctx = canvasObj.getContext("2d"),
canvasObj.width = canvas.canvas_w;
canvasObj.height = canvas.canvas_h;
}else{
console.log("当前环境不支持canvas");
return null;
}
setInterval(function(){
self.createline(self,canvas);
if(canvas.fx == "w"){
self.updateline_w(self,canvas);
}
if(canvas.fx == "h"){
self.updateline_h(self,canvas);
}
self.addline(self,canvas);
},config.time);
return canvas.ctx;
}
//画线
Createline.prototype.createline = function(self,canvas){
var content = canvas.ctx;
content.clearRect(0,0,canvas.canvas_w,canvas.canvas_h);
for(var i = 0 ; i < self.lines.length ; i++){
content.beginPath();
content.moveTo(self.lines[i].mx,self.lines[i].my);
//线经过的转折点或结束点
content.lineTo(self.lines[i].lx,self.lines[i].ly);
//线条宽度
content.lineWidth = canvas.line_w;
content.strokeStyle = canvas.color;
content.stroke();
//线条颜色
content.closePath();
//画线
}
}
//改变数据 水平运动
Createline.prototype.updateline_w = function(self,canvas){
for (var i = 0 ; i < self.lines.length ; i++) {
self.lines[i].mx = self.lines[i].mx + self.lines[i].vx;
self.lines[i].lx = self.lines[i].lx + self.lines[i].vx;
}
//超出画布的线条从数组内删除,减少系统消耗
var cnt = [];
for (var j = 0 ;j < self.lines.length ; j++) {
if(self.lines[j].lx > canvas.canvas_w){
cnt.push(j);
}
}
for(var k = 0; k < cnt.length ; k++){
self.lines.splice(k,1);
}
}
//改变数据 垂直运动
Createline.prototype.updateline_h = function(self,canvas){
for (var i = 0 ; i < self.lines.length ; i++) {
self.lines[i].my = self.lines[i].my + lines[i].vy;
self.lines[i].ly = self.lines[i].ly + lines[i].vy;
}
//超出画布的线条从数组内删除,减少系统消耗
var cnt = [];
for (var j = 0 ;j < self.lines.length ; j++) {
if( self.lines[j].ly > canvas.canvas_h){
cnt.push(j);
}
}
for(var k = 0; k < cnt.length ; k++){
self.lines.splice(k,1);
}
}
//增加线
Createline.prototype.addline = function(self,canvas){
var length = self.lines.length;
//横线
if(canvas.fx == "w"){
//判断是否需要生成线
if(self.lines[length-1].lx > 0){
//起点位置 等于 左右一根线的坐标减去间隔
var ww = self.lines[length - 1].lx - canvas.jiange;
//判断长短
if(self.c == 0){
var jg = canvas.width;
self.c = 10;
}else{
var jg = canvas.width/2;
self.c = 0;
}
var lxx = ww - jg;
var data = {
mx:ww,
lx:lxx,
my:canvas.my,
ly:canvas.ly,
vx:canvas.vx,
vy:canvas.vy,
}
self.lines.push(data);
}
}
//垂直
if(canvas.fx == "h"){
if(length>0){
//判断是否需要生成线
if(self.lines[length-1].ly > 0){
//起点位置 等于 左右一根线的坐标减去间隔
var my = self.lines[length - 1].ly - canvas.jiange;
//判断长短
if(c == 0){
var jg = canvas.width;
c = 10;
}else{
var jg = canvas.width/2;
c = 0;
}
var ly = my - jg;
var data = {
mx:canvas.mx,
lx:canvas.lx,
my:my,
ly:ly,
vx:canvas.vx,
vy:canvas.vy,
}
self.lines.push(data);
}
}else{
var data = {
mx:canvas.mx,
my:canvas.my,
lx:canvas.lx,
ly:canvas.ly,
vx:canvas.vx,
vy:canvas.vy,
}
self.lines.push(data);
}
}
}
export{
Createline
}
You need to use new when creating a instance for a constructor that uses this:
var cre = new Createline(data);
When a function is executed using new it does the following:
function User(name) {
// this = {}; (implicitly)
// add properties to this
this.name = name;
this.isAdmin = false;
// return this; (implicitly)
}

How can I make this Index script show more than 150 results in Blogger?

I have been using this script which was great but unfortunately it will only show the most recent 150 results even if I change the parameter and I have more that many posts.
I guess the best result would be to break it up with results A-M , N-Z but I don't know how to do that. Any help would be much appreciated.
<div>
<ul id="postList12"></ul>
</div>
<script type="text/javascript">
var startIndex = 1;
var maxResults = 999;
var allResults = [];
function sendQuery12()
{
var scpt = document.createElement("script");
scpt.src = "/feeds/posts/summary?alt=json&callback=processPostList12&start-index=" + startIndex + "&max-results=" + maxResults;
document.body.appendChild(scpt);
}
function printArrayResults(root)
{
//Sort Alphebetically
allResults.sort(function(a, b){
var a_string = a.children[0].textContent ;
var b_string = b.children[0].textContent ;
if(a_string < b_string) return -1;
if(a_string > b_string) return 1;
return 0;
})
var elmt = document.getElementById("postList12");
for (index = 0; index < allResults.length; index++) {
elmt.appendChild(allResults[index]);
}
}
function processPostList12(root)
{
var elmt = document.getElementById("postList12");
if (!elmt)
return;
var feed = root.feed;
if (feed.entry.length > 0)
{
for (var i = 0; i < feed.entry.length; i++)
{
var entry = feed.entry[i];
var title = entry.title.$t
for (var j = 0; j < entry.link.length; j++)
{
if (entry.link[j].rel == "alternate")
{
var url = entry.link[j].href;
if (url && url.length > 0 && title && title.length > 0)
{
var liE = document.createElement("li");
var a1E = document.createElement("a");
a1E.href = url;
a1E.textContent = title;
liE.appendChild(a1E);
//elmt.appendChild(liE);
allResults.push(liE);
}
break;
}
}
}
if (feed.entry.length >= maxResults)
{
startIndex += maxResults;
sendQuery12();
} else {
printArrayResults();
}
}
}
sendQuery12();
</script>

variable assignment doesn't work javascript

In the following code, the console.log from the line 92 and 93 (switchPosition function) doesn't provide the same result. I am, I have to admit, stuck.
Any thoughts, ideas, explanations?
Thanks you for the time taken,
var Carrousel = (function () {
var self = {},
config = {
item: 3, // item to be displayed
scroll: 2 // number of items to be scrolled
},
container = null,
items = null,
nbItems = null,
nbSlide = null,
position = [],
searchPositionDepending = []
;
self.init = function (opts) {
options = opts || {}
execute();
}
// Private Method
execute = function () {
container = document.getElementById('carrousel');
items = document.getElementsByClassName('flux');
var containerWidth = container.offsetWidth;
var containerHeight = items[0].offsetHeight * 1.5;
container.style.height = '' + containerHeight + '';
nbItems = document.getElementsByClassName('flux').length;
nbSlide = nbItems / config.item;
// Initialisation du Carrousel
for (i = 0; i < nbItems; i++) {
items[i].style.width = '' + (containerWidth / config.item) + '';
items[i].style.display = 'none';
items[i].style.position = 'absolute';
items[i].style.top = "0";
items[i].style.left = "0";
items[i].setAttribute('data-position', '' + (i + 1) + '');
items[i].setAttribute('data-number', '' + i + '');
}
searchPosition();
placement();
document.getElementById('next').onclick = function () {
next();
searchPosition();
switchPosition();
placement();
// position();
}
document.getElementById('previous').onclick = function () {
// previous();
// searchPosition();
// position();
}
}
searchPosition = function () {
for (i = 0; i < config.item; i++) {
searchPositionDepending[i] = (function () { //Appending a function searchPosition per item displayed
for (j = 1; j <= config.item; j++) { //Passing through the first items to get their position
if (items[i].dataset.position === '' + j + '') {
position[j] = items[i];
return true;
} else {
}
}
;
})();
}
}
switchPosition = function () {
for (i = 0, j = 0; i < nbItems; i++, j++) {
if (items[i].dataset.position === '' + j + '') {
position[i] = position[i];
}
}
for (i = config.item, j = 1; i < nbItems; i++, j++) { //Replacing in good order, except for the one that are place into the variable position[];
items[i] = items[j];
}
for (i = (nbItems - config.item +1), j = 1; i <= nbItems; i++, j++) { //Replacing in good order the one that are place into variable position[];
items[i] = position[j];
console.log(i);
console.log(j);
console.log(position[j]);
console.log(items[i]);
}
for (i = 0; i < nbItems; i++) {
console.log(items[i]);
}
console.log(items[10]);
}
placement = function () {
for (i = 1; i <= config.item; i++) {
var rect = items[0].getBoundingClientRect();
item_width = Math.floor(rect.width);
item_height = Math.floor(rect.height);
var x = item_width * (i - 1) * 1.1;
items[i].style.display = 'block';
items[i].style.transform = "translate3D(" + x + "px, 0px, 0px)";
}
}
next = function () {
for (i = config.item, j = 1; i < nbItems; i++, j++) { //Updating all dataset position, except for the items that are displayed.
items[i].dataset.position = j;
}
for (i = 1, j = 2; i <= config.item; i++, j--) {
position[i].dataset.position = nbItems - j;
position[i].style.display = "none";
}
}
return self;
})();

'Arc is not a constructor' error

I am getting an error saying Arc is not a constructor. I have checked my code and can't understand why.
/*
Exception: Arc is not a constructor
RouteFinder/this.getPairs#Scratchpad/8:72:6
#Scratchpad/8:5:3
*/
The other answers for this error suggest that this because Arc has previously been defined, but I cant find anywhere that it is. This is a big chunk of code, so scroll down for the error - it is commented where it is
var lats = [ 51.445371, 51.45526, 51.426765, 51.441304 ]
var lons = [ -0.077581, -0.113248, -0.13091, -0.060596 ]
var finder = new RouteFinder(lats, lons);
finder.getPairs();
var nodeList = ''
for(var count = 1; count < lats.length; count++) {
nodeList += count;
}
finder.permutation("", nodeList);
finder.removeDuplicateRoutes();
var shortestRoute = finder.getShortestRoute();
var finalRouteOrder = [];
shortestRoute.nodeList.forEach(function(node) {
finalRouteOrder.push(+node);
});
alert(finalRouteOrder);
var Route = function() {
this.totalWeight = 0;
this.nodeList = [];
};
var Node = function() {
this.lat = 0;
this.lon = 0;
this.number = 0;
};
var Arc = function() {
this.startNode = new Node();
this.endNode = new Node();
this.weight = 0;
};
function reverseString(initialString) {
var reversed = '';
for(var count = initialString.length -1; count > -1; count--) {
reversed += initialString.charAt(count);
}
return reversed;
}
function calcDistance(lat1, lng1, lat2, lng2) {
var earthRadius = 6371;
var dLat = (lat2 - lat1)/180*Math.PI;
var dLng = (lng2 - lng1)/180*Math.PI;
var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1/180*Math.PI) * Math.cos(lat2/180*Math.PI) * Math.sin(dLng/2) * Math.sin(dLng/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var dist = earthRadius * c;
return dist;
}
function RouteFinder(lats, lons) {
this.latArray = lats;
this.lonArray = lons;
this.orders = [];
this.arcArray = [];
this.routes = [];
this.shortestRoute;
this.numOfPoints = lats.length - 1;
this.shortestRouteLength = -1;
this.getPairs = function() {
var timesLooped = 0;
for(var count1 = 0; count1 < this.numOfPoints; count1++) {
for(var count2 = 0; count2 < (this.numOfPoints - count1); count2++) {
//I get an error here for new Arc()
this.arcArray.push(new Arc());
this.arcArray[timesLooped].startNode = {
number: count1,
};
this.arcArray[timesLooped].endNode = {
number: this.numOfPoints - count2,
};
this.arcArray[timesLooped].weight = calcDistance(this.latArray[count1], this.lonArray[count1], this.latArray[this.numOfPoints - count2], this.lonArray[this.numOfPoints - count2]);
timesLooped++;
}
}
};
this.permutation = function(prefix, str) {
var n = str.length;
if(n === 0) this.orders.push('0' + prefix + '0');
else {
for(var i = 0; i <n; i++) {
this.permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
}
}
};
this.removeDuplicateRoutes = function() {
var numberOfPermutations = this.orders.length -1;
var temp;
var size;
var toRemove = [];
for(var count1 = 0; count1 < numberOfPermutations; count1++) {
for(var count2 = 0; count2 < (numberOfPermutations - count1); count2++) {
if(this.orders[count1] == reverseString(this.orders[numberOfPermutations - count2])) {
toRemove.push(count1);
}
}
}
size = toRemove.length;
for(var count3 = 0; count3 < size; count3++) {
temp = toRemove[size - 1- count3];
var index = this.orders.indexOf(temp);
if(index > -1) {
temp.splice(index, 1);
}
}
};
this.getShortestRoute = function() {
var routesMade = 0;
for(var routeNumber = 0; routeNumber < (this.orders.length -1); routeNumber++) {
this.routes.push(new Route());
this.routes[routesMade].totalWeight = 0;
for(var count1 = 0; count1 < this.orders[routeNumber].length; count1++) {
this.routes[routesMade].nodeList.push(+this.orders[routeNumber].charAt(count1));
}
for(var count2 = 1; count2 < this.orders[routeNumber].length; count2++) {
for(var count3 = 0; count3 < this.arcArray.length; count3++) {
if(this.routes[routesMade].nodeList[count2 - 1] === this.arcArray[count3].startNode.number) {
if(this.routes[routesMade].nodeList[count2] === this.arcArray[count3].endNode.number) {
this.routes[routesMade].totalWeight += this.arcArray[count3].weight;
}
} else if (this.routes[routesMade].nodeList[count2 - 1] === this.arcArray[count3].endNode.number) {
if(this.routes[routesMade].nodeList[count2] === this.arcArray[count3].startNode.number) {
this.routes[routesMade].totalWeight += this.arcArray[count3].weight;
}
}
}
}
if(!this.shortestRoute) {
this.shortestRoute = this.routes[routesMade];
} else if(this.routes[routesMade].totalWeight < this.shortestRoute.totalWeight) {
this.shortestRoute = this.routes[routesMade];
}
routesMade++;
}
return this.shortestRoute;
};
}
I'm tearing my hair out trying to work out the problem. Help is greatly appreciated, thanks!
This
var finder = new RouteFinder(lats, lons);
gets executed before Arc variable gets its value (function). Thus at the moment of RouteFinder call that Arc variable is undefined and cannot be used as a constructor.
Update: it is about finder.getPairs(); actually where you try to call that new Arc();
You need to have Route, Node, and Arc like this:
function Route() {
this.totalWeight = 0;
this.nodeList = [];
}
function Node() {
this.lat = 0;
this.lon = 0;
this.number = 0;
}
function Arc() {
this.startNode = new Node();
this.endNode = new Node();
this.weight = 0;
}
The issue is that Arc is not yet defined. Either move your function expression assignment (var Arc = function ...) to the top of your script or convert them to function definition statements like this
function Arc() {
this.startNode = new Node();
this.endNode = new Node();
this.weight = 0;
}
Statements are hoisted and their order does not matter, but assignment to var happens in the order they appear in the file (the declaration is hoisted, but the assignment isn't).
Same goes for your Route and Node functions.
Read more about var hoisting on MDN.

Categories

Resources