React State cannot update array with intervals correctly - reactjs

I'm trying to make a simple animation with JS: I want to randomise a series of letters of a title for an interval of time and after a timeout set the title to the company title basically.
Here's the code I've written so far:
const alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
"O", "P", "Q", "R", "S", "T", "I", "U", "V", "W", "X", "Y", "Z", "~", "&", "|", "^", "ç", "#", "]",
"[", "{", "}", "ù", "*", "µ", "¤", "$", "£", "€", "°", ")", "(", "+", "-", "/", "<", ">", "²", "`", "é",
"è", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"];
const randomFromAlphabet = () => alphabet[(Math.floor(Math.random() * alphabet.length))];
const companyTitle = ['C', 'U', 'I', 'R', 'C', 'K'];
const AboutUs = () => {
const [title, setTitle] = useState(Array.from({ length: companyTitle.length }, () => randomFromAlphabet()));
const [intervals, setIntervals] = useState([]);
const letterRandomize = () => {
const generatedIntervals = Array.from({ length: title.length }, (_, index) => {
return setInterval(() => {
const arrayTitle = Array.from(title);
arrayTitle[index] = randomFromAlphabet();
setTitle(arrayTitle);
}, 350 * (index + 1));
});
setIntervals(generatedIntervals);
};
useEffect(() => {
letterRandomize();
setTimeout(() => {
for (var i = 0; i < companyTitle.length; i++) {
clearInterval(intervals[i]);
const newTitle = [...title];
newTitle[i] = companyTitle[i];
setTitle(newTitle);
}
}, 3000)
}, []);
I know it's not very good written, it's because I'm trying to understand what the problem is.
I've encountered two problems: the first one is the update of the randomised letters:
I've noticed that everytime I update one letter of the array the other go back to the originals.
So for example if we have 'CUIRCK' and after one update we have 'CAIRCK' after another update the second letter returns to 'U', like 'CUIRCB'.
The second problem is that I cannot clear the intervals. I've created 6 different intervals and put them in my state, I don't what I'm doing wrong.

just created a Sandbox which should solve your problem. State inside Intervals can be tricky and you should avoid it. SetState is running async, since setInterval also runs your function async inside an interval you are referring to a state which could not have been already updated to the value you want. I hope I explained myself well enough.
https://codesandbox.io/s/randomized-title-oozo6

Related

How to get multiple elements from an Array?

I'm using discord.js and I want to create a "server" with passcode. I want the passcode to be 6 letters long, so far I can only do one.
It has to be random as well. Like "ZSHWJK" Instead of "AAAAAA"
Code:
var serverPasscode = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
module.exports = {
name: "createserver",
description: "Creates a server",
run(message, args, client){
const newServer = new MessageEmbed()
.setTitle(`${message.author.name}'s server`)
.setFooter(`${serverPasscode[Math.floor(Math.random() * serverPasscode.length)]}`)
message.channel.send(newServer);
}
};
Right now this can only return one element which is not what I want.
You could use a for loop and create a function such as this:
function makeGuildPassword(length) {
var result = ''; // create empty string that you will add random characters to
var characters = // list of characters (you can change this however you want)
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i = 0; i < length; i++) { // create a loop
// add a random character to the string; restart the loop
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
};
console.log(makeGuildPassword(6))

Replace all 'A' present in an Array with '15' in Swift 3

I want to replace all A characters present in an array with 15 using Swift 3.
Example array:
["4", "5", "6", "A", "A", "Q", "A"]
Desired result:
["4", "5", "6", "15", "15", "Q", "15"]
map to the rescue:
var a = ["4", "5", "6", "A", "A", "Q", "A"]
a = a.map({ $0 == "A" ? "15" : $0 })
print(a)// ["4", "5", "6", "15", "15", "Q", "15"]
EDIT: After error screenshot:
You have an array of characters and hence the above code is not working. Also, remember "15" is two characters and not one character. Hence, I have replaced character 'A' with string "15" and mapped it to an array of strings, instead
let player1 = "456AAQA"
var player1Cards = Array(player1.characters) // ["4", "5", "6", "A", "A", "Q", "A"]
var player1CardsStrings = player1Cards.map{$0 == "A" ? "15" : String($0)}
player1CardsStrings // ["4", "5", "6", "15", "15", "Q", "15"]
Tested on Playground.
Because your question is lacking information that you didn't gave at first, here is what you can do.
"for loop": You iterate and replace the value if needed.
That's a logic you could apply on almost all languages.
var array1 = ["4", "5", "6", "A", "A", "Q", "A"]
for index in 0 ... array1.count-1
{
if array1[index] == "A"
{
array1[index] = "15"
}
}
print("array1: \(array1)")
"for each loop": You iterate and replace the value if needed.
That's a logic you could apply on almost all languages (maybe less languages that the previous one)
var array2 = ["4", "5", "6", "A", "A", "Q", "A"]
for (index, object) in array2.enumerated()
{
if object == "A"
{
array2[index] = "15"
}
}
print("array2: \(array2)")
"map": the "map" iterate for you (here is the important part behind the magic), you check the value and replace the value if needed. The $0 represent the "current item".
Here is a specificity.
var array3 = ["4", "5", "6", "A", "A", "Q", "A"]
array3 = array3.map({
if $0 == "A"
{
return "15"
}
return $0
})
print("array3: \(array3)")
"map": the "map" iterate for you, you check the value and replace the value if needed with a ternary if test.
var array4 = ["4", "5", "6", "A", "A", "Q", "A"]
array4 = array4.map({$0 == "A" ? "15" : $0})
print("array4: \(array4)")
I'm gave 4 ways (I've could also have explicit more the map() with explicit closure, from the simplest to the more complicated. We can't know if you don't show your attempts where you are are stucked. Is it for loop? The basic algorithms?
Swift advanced user may be more fond of the last one, but for beginners, it's quite complex and "magic". So when they want to change it a little for a different test, they never know what to do.
Side note: I'm not a Swift developer, more an Objective-C, so it may be lacking of checks. This answers is to show different approaches, how you go from a "verbose" to a less "verbose" code, but that you need to master anyway. Even if you have issue with map(), you can "bypass" it and do it manually.
let values = ["4", "5", "6", "A", "A", "Q", "A"]
let mappedvalues = values.map({ (value: String) -> String in
if value != "A" {
return value
}
return "15"
})

How to generate random string form array of elements by compared with another array of elements in swift?

I aware to get random character from a string. From here is the code,
func randomString(_ length: Int) -> String {
let master = Array("abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ_123456789".characters) //0...62 = 63
var randomString = ""
for _ in 1...length{
let random = arc4random_uniform(UInt32(master.count))
randomString.append(String(master[Int(random)]))
}
return randomString
}
Usage :
var randomArray1 = [String]()
for _ in 0...62{
randomArray1.append(self.randomString(1))
}
Here, If randomArray1.append(self.randomString(x)), then x = 1...N
Checking repeated elements :
var sameElementCatcher = [String]()
for x in 0...62{
let element = randomArray1[x]
randomArray1[x] = ""
if randomArray1.contains(element){
sameElementCatcher.append(element)
}
}
print("Same Elements")
print(sameElementCatcher.count != 0 ? sameElementCatcher : "Array count is zero")
Output:
Same Elements
["_", "u", "8", "7", "E", "P", "u", "y", "C", "-", "C", "x", "l", "j",
"t", "D", "U", "2", "e", "2"]
But I need to get array of 62 unique random characters from master by compared with randomArray1. i.e., Array count is zero
How can I achieve this without delay?
Note:
Also, I read this post also I have a answer for shuffling array. But this post different from shuffling only, Please, see usage.
Did you try like this?
What I understand from your question. generate a random text where all the characters are unique.
Before appending your random string to your array check is array have that char then append into your array.
func randomString(_ length: Int) -> String {
let master = Array("abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ_123456789".characters) //0...62 = 63
var randomString = ""
for _ in 1...length{
let random = arc4random_uniform(UInt32(master.count))
randomString.append(String(master[Int(random)]))
}
return randomString
}
var randomArray1 = [String]()
var tempRandomString = ""
let totalRandomCount = 62
var randomArrayCount = 0
while (totalRandomCount > randomArrayCount) {
tempRandomString = randomString(1)
if !randomArray1.contains(tempRandomString) {
randomArray1.append(tempRandomString)
randomArrayCount+=1
}
}
print(randomArray1)
Output: ["X", "u", "j", "1", "n", "E", "D", "q", "U", "6", "T", "O", "f", "J", "i", "c", "W", "V", "G", "R", "k", "7", "_", "8", "-", "l", "w", "4", "e", "Q", "C", "m", "M", "Y", "o", "S", "B", "2", "Z", "P", "p", "N", "y", "H", "a", "h", "z", "s", "b", "A", "3", "g", "x", "L", "v", "F", "d", "r", "t", "K", "9", "5"]
I tried this with playground. For this output 199 times loop executed.
If anyone knows better than this update yours.

Swift live text field checking for characters from multiple arrays [duplicate]

This question already has answers here:
Check password string strength criteria in Swift
(2 answers)
Closed 6 years ago.
I have a text field which will serve as a password input. I have created 4 arrays
upperCaseAll = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
lowerCaseAll = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
numberAll = [1 ,2, 3, 4, 5, 6, 7, 8, 9, 0]
specialCharAll = ["-", "/", ":", ";", "(", ")", "$", "&", "#", "\"", ".", ",", "?", "!", "'", "[", "]", "{", "}", "#", "%", "^", "\\", "|", "~", "<", ">", "€", "£", "¥", "•", ".", ","]
I am trying to make the user type at least one of each type of character.
I have 4 text views that will turn from red to green once each rule is met.
Then when all rules are met the red text views turn green and the login button is enabled
My question is how do I live check the text field to see if it has satisfied a rule? I imagine it would have to check each of the arrays overtime a character is entered
Oh also should the numbers be Ints or Strings?
Thanks
It's easier if you use Set instead of Array. Here's an example:
private let upperCaseAll = Set("ABCDEFGHIJKLMNOPQRSTUVWXYZ".characters)
private let lowerCaseAll = Set("abcdefghijklmnopqrstuvwxyz".characters)
private let numberAll = Set("0123456789".characters)
private let specialCharAll = Set("-/:;()$&#\".,?!'[]{}#%^\\|~<>€£¥".characters)
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// Determines what the new value of the text field will be
let newText = range.length == 0 ? textField.text! + string : (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
// Turn that string into a Set of Characters
let characters = Set(newText.characters)
let hasUpperCase = !characters.intersect(self.upperCaseAll).isEmpty
let hasLowerCase = !characters.intersect(self.lowerCaseAll).isEmpty
let hasNumber = !characters.intersect(self.numberAll).isEmpty
let hasSpecialChar = !characters.intersect(self.specialCharAll).isEmpty
// Now turn your 4 other views to green/red as needed
print("hasUpperCase = \(hasUpperCase), hasLowercase = \(hasLowerCase), hasNumber = \(hasNumber), hasSpecialChar = \(hasSpecialChar)")
...
return true
}
You can do it using the UITextFieldDelegate
See Apple Docs - textField(_:shouldChangeCharactersInRange:replacementString:)
The text field calls this method whenever user actions cause its text
to change. Use this method to validate text as it is typed by the
user. For example, you could use this method to prevent the user from
entering anything but numerical values.
But you should think about using a regex to check the password string. That would be more convenient.

Angular Service returns String as dictionary

I have a service as
angular.module('inviteService', ['ngResource']).factory('Invite', function ($resource) {
return $resource('/invite');
});
and my controller is
$scope.invite = function () {
console.log("submitting invite for " + $scope.email);
var invite = new Invite();
Invite.save({'email': $scope.email}, function (data) {
console.log('data is: ' + data);
$scope.message.type = 'info';
$scope.message.content = data;
// console.log('controller message' + JSON.stringify($scope.message, null, 2));
// reset email input box
$scope.email = undefined;
});
and relevant directive code as
scope.$watch('ngModel', function () {
if (Object.keys(scope.ngModel).length > 0) {
console.log('directive message: ' + JSON.stringify(scope.ngModel));
element.show();
//noinspection JSUnresolvedFunction
$timeout(function () {
//element.empty();
element.fadeOut("slow");
}, 1000);
}
}, true);
When I run the code, I see in Chrome Network tab the response as
"You are already on our invite list"
But the Angular code console shows me
data is: [object Object] notificationController.js:13
directive message:{
"type": "info",
"content": {
"0": "\"",
"1": "Y",
"2": "o",
"3": "u",
"4": " ",
"5": "a",
"6": "r",
"7": "e",
"8": " ",
"9": "a",
"10": "l",
"11": "r",
"12": "e",
"13": "a",
"14": "d",
"15": "y",
"16": " ",
"17": "o",
"18": "n",
"19": " ",
"20": "o",
"21": "u",
"22": "r",
"23": " ",
"24": "i",
"25": "n",
"26": "v",
"27": "i",
"28": "t",
"29": "e",
"30": " ",
"31": "l",
"32": "i",
"33": "s",
"34": "t",
"35": "\""
}
}
Why is that data is not coming as string?
ngResource expects an object or an array of objects in the response from the server.
See https://stackoverflow.com/a/13816008/215945 for your options:
use $http instead of $resource
return an object from your server (probably the easiest approach, if you can modify the server): { "str": "'You are...'"}
intercept and modify the returned value (probably too much work)

Resources